All files / P1-import-Subsystem/public/js bundle-1753229075.js

0% Statements 0/14318
0% Branches 0/8456
0% Functions 0/2548
0% Lines 0/13805

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409 18410 18411 18412 18413 18414 18415 18416 18417 18418 18419 18420 18421 18422 18423 18424 18425 18426 18427 18428 18429 18430 18431 18432 18433 18434 18435 18436 18437 18438 18439 18440 18441 18442 18443 18444 18445 18446 18447 18448 18449 18450 18451 18452 18453 18454 18455 18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472 18473 18474 18475 18476 18477 18478 18479 18480 18481 18482 18483 18484 18485 18486 18487 18488 18489 18490 18491 18492 18493 18494 18495 18496 18497 18498 18499 18500 18501 18502 18503 18504 18505 18506 18507 18508 18509 18510 18511 18512 18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524 18525 18526 18527 18528 18529 18530 18531 18532 18533 18534 18535 18536 18537 18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550 18551 18552 18553 18554 18555 18556 18557 18558 18559 18560 18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575 18576 18577 18578 18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592 18593 18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609 18610 18611 18612 18613 18614 18615 18616 18617 18618 18619 18620 18621 18622 18623 18624 18625 18626 18627 18628 18629 18630 18631 18632 18633 18634 18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645 18646 18647 18648 18649 18650 18651 18652 18653 18654 18655 18656 18657 18658 18659 18660 18661 18662 18663 18664 18665 18666 18667 18668 18669 18670 18671 18672 18673 18674 18675 18676 18677 18678 18679 18680 18681 18682 18683 18684 18685 18686 18687 18688 18689 18690 18691 18692 18693 18694 18695 18696 18697 18698 18699 18700 18701 18702 18703 18704 18705 18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732 18733 18734 18735 18736 18737 18738 18739 18740 18741 18742 18743 18744 18745 18746 18747 18748 18749 18750 18751 18752 18753 18754 18755 18756 18757 18758 18759 18760 18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794 18795 18796 18797 18798 18799 18800 18801 18802 18803 18804 18805 18806 18807 18808 18809 18810 18811 18812 18813 18814 18815 18816 18817 18818 18819 18820 18821 18822 18823 18824 18825 18826 18827 18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852 18853 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912 18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957 18958 18959 18960 18961 18962 18963 18964 18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015 19016 19017 19018 19019 19020 19021 19022 19023 19024 19025 19026 19027 19028 19029 19030 19031 19032 19033 19034 19035 19036 19037 19038 19039 19040 19041 19042 19043 19044 19045 19046 19047 19048 19049 19050 19051 19052 19053 19054 19055 19056 19057 19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087 19088 19089 19090 19091 19092 19093 19094 19095 19096 19097 19098 19099 19100 19101 19102 19103 19104 19105 19106 19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117 19118 19119 19120 19121 19122 19123 19124 19125 19126 19127 19128 19129 19130 19131 19132 19133 19134 19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148 19149 19150 19151 19152 19153 19154 19155 19156 19157 19158 19159 19160 19161 19162 19163 19164 19165 19166 19167 19168 19169 19170 19171 19172 19173 19174 19175 19176 19177 19178 19179 19180 19181 19182 19183 19184 19185 19186 19187 19188 19189 19190 19191 19192 19193 19194 19195 19196 19197 19198 19199 19200 19201 19202 19203 19204 19205 19206 19207 19208 19209 19210 19211 19212 19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225 19226 19227 19228 19229 19230 19231 19232 19233 19234 19235 19236 19237 19238 19239 19240 19241 19242 19243 19244 19245 19246 19247 19248 19249 19250 19251 19252 19253 19254 19255 19256 19257 19258 19259 19260 19261 19262 19263 19264 19265 19266 19267 19268 19269 19270 19271 19272 19273 19274 19275 19276 19277 19278 19279 19280 19281 19282 19283 19284 19285 19286 19287 19288 19289 19290 19291 19292 19293 19294 19295 19296 19297 19298 19299 19300 19301 19302 19303 19304 19305 19306 19307 19308 19309 19310 19311 19312 19313 19314 19315 19316 19317 19318 19319 19320 19321 19322 19323 19324 19325 19326 19327 19328 19329 19330 19331 19332 19333 19334 19335 19336 19337 19338 19339 19340 19341 19342 19343 19344 19345 19346 19347 19348 19349 19350 19351 19352 19353 19354 19355 19356 19357 19358 19359 19360 19361 19362 19363 19364 19365 19366 19367 19368 19369 19370 19371 19372 19373 19374 19375 19376 19377 19378 19379 19380 19381 19382 19383 19384 19385 19386 19387 19388 19389 19390 19391 19392 19393 19394 19395 19396 19397 19398 19399 19400 19401 19402 19403 19404 19405 19406 19407 19408 19409 19410 19411 19412 19413 19414 19415 19416 19417 19418 19419 19420 19421 19422 19423 19424 19425 19426 19427 19428 19429 19430 19431 19432 19433 19434 19435 19436 19437 19438 19439 19440 19441 19442 19443 19444 19445 19446 19447 19448 19449 19450 19451 19452 19453 19454 19455 19456 19457 19458 19459 19460 19461 19462 19463 19464 19465 19466 19467 19468 19469 19470 19471 19472 19473 19474 19475 19476 19477 19478 19479 19480 19481 19482 19483 19484 19485 19486 19487 19488 19489 19490 19491 19492 19493 19494 19495 19496 19497 19498 19499 19500 19501 19502 19503 19504 19505 19506 19507 19508 19509 19510 19511 19512 19513 19514 19515 19516 19517 19518 19519 19520 19521 19522 19523 19524 19525 19526 19527 19528 19529 19530 19531 19532 19533 19534 19535 19536 19537 19538 19539 19540 19541 19542 19543 19544 19545 19546 19547 19548 19549 19550 19551 19552 19553 19554 19555 19556 19557 19558 19559 19560 19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572 19573 19574 19575 19576 19577 19578 19579 19580 19581 19582 19583 19584 19585 19586 19587 19588 19589 19590 19591 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623 19624 19625 19626 19627 19628 19629 19630 19631 19632 19633 19634 19635 19636 19637 19638 19639 19640 19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653 19654 19655 19656 19657 19658 19659 19660 19661 19662 19663 19664 19665 19666 19667 19668 19669 19670 19671 19672 19673 19674 19675 19676 19677 19678 19679 19680 19681 19682 19683 19684 19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701 19702 19703 19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716 19717 19718 19719 19720 19721 19722 19723 19724 19725 19726 19727 19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739 19740 19741 19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760 19761 19762 19763 19764 19765 19766 19767 19768 19769 19770 19771 19772 19773 19774 19775 19776 19777 19778 19779 19780 19781 19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796 19797 19798 19799 19800 19801 19802 19803 19804 19805 19806 19807 19808 19809 19810 19811 19812 19813 19814 19815 19816 19817 19818 19819 19820 19821 19822 19823 19824 19825 19826 19827 19828 19829 19830 19831 19832 19833 19834 19835 19836 19837 19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854 19855 19856 19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885 19886 19887 19888 19889 19890 19891 19892 19893 19894 19895 19896 19897 19898 19899 19900 19901 19902 19903 19904 19905 19906 19907 19908 19909 19910 19911 19912 19913 19914 19915 19916 19917 19918 19919 19920 19921 19922 19923 19924 19925 19926 19927 19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942 19943 19944 19945 19946 19947 19948 19949 19950 19951 19952 19953 19954 19955 19956 19957 19958 19959 19960 19961 19962 19963 19964 19965 19966 19967 19968 19969 19970 19971 19972 19973 19974 19975 19976 19977 19978 19979 19980 19981 19982 19983 19984 19985 19986 19987 19988 19989 19990 19991 19992 19993 19994 19995 19996 19997 19998 19999 20000 20001 20002 20003 20004 20005 20006 20007 20008 20009 20010 20011 20012 20013 20014 20015 20016 20017 20018 20019 20020 20021 20022 20023 20024 20025 20026 20027 20028 20029 20030 20031 20032 20033 20034 20035 20036 20037 20038 20039 20040 20041 20042 20043 20044 20045 20046 20047 20048 20049 20050 20051 20052 20053 20054 20055 20056 20057 20058 20059 20060 20061 20062 20063 20064 20065 20066 20067 20068 20069 20070 20071 20072 20073 20074 20075 20076 20077 20078 20079 20080 20081 20082 20083 20084 20085 20086 20087 20088 20089 20090 20091 20092 20093 20094 20095 20096 20097 20098 20099 20100 20101 20102 20103 20104 20105 20106 20107 20108 20109 20110 20111 20112 20113 20114 20115 20116 20117 20118 20119 20120 20121 20122 20123 20124 20125 20126 20127 20128 20129 20130 20131 20132 20133 20134 20135 20136 20137 20138 20139 20140 20141 20142 20143 20144 20145 20146 20147 20148 20149 20150 20151 20152 20153 20154 20155 20156 20157 20158 20159 20160 20161 20162 20163 20164 20165 20166 20167 20168 20169 20170 20171 20172 20173 20174 20175 20176 20177 20178 20179 20180 20181 20182 20183 20184 20185 20186 20187 20188 20189 20190 20191 20192 20193 20194 20195 20196 20197 20198 20199 20200 20201 20202 20203 20204 20205 20206 20207 20208 20209 20210 20211 20212 20213 20214 20215 20216 20217 20218 20219 20220 20221 20222 20223 20224 20225 20226 20227 20228 20229 20230 20231 20232 20233 20234 20235 20236 20237 20238 20239 20240 20241 20242 20243 20244 20245 20246 20247 20248 20249 20250 20251 20252 20253 20254 20255 20256 20257 20258 20259 20260 20261 20262 20263 20264 20265 20266 20267 20268 20269 20270 20271 20272 20273 20274 20275 20276 20277 20278 20279 20280 20281 20282 20283 20284 20285 20286 20287 20288 20289 20290 20291 20292 20293 20294 20295 20296 20297 20298 20299 20300 20301 20302 20303 20304 20305 20306 20307 20308 20309 20310 20311 20312 20313 20314 20315 20316 20317 20318 20319 20320 20321 20322 20323 20324 20325 20326 20327 20328 20329 20330 20331 20332 20333 20334 20335 20336 20337 20338 20339 20340 20341 20342 20343 20344 20345 20346 20347 20348 20349 20350 20351 20352 20353 20354 20355 20356 20357 20358 20359 20360 20361 20362 20363 20364 20365 20366 20367 20368 20369 20370 20371 20372 20373 20374 20375 20376 20377 20378 20379 20380 20381 20382 20383 20384 20385 20386 20387 20388 20389 20390 20391 20392 20393 20394 20395 20396 20397 20398 20399 20400 20401 20402 20403 20404 20405 20406 20407 20408 20409 20410 20411 20412 20413 20414 20415 20416 20417 20418 20419 20420 20421 20422 20423 20424 20425 20426 20427 20428 20429 20430 20431 20432 20433 20434 20435 20436 20437 20438 20439 20440 20441 20442 20443 20444 20445 20446 20447 20448 20449 20450 20451 20452 20453 20454 20455 20456 20457 20458 20459 20460 20461 20462 20463 20464 20465 20466 20467 20468 20469 20470 20471 20472 20473 20474 20475 20476 20477 20478 20479 20480 20481 20482 20483 20484 20485 20486 20487 20488 20489 20490 20491 20492 20493 20494 20495 20496 20497 20498 20499 20500 20501 20502 20503 20504 20505 20506 20507 20508 20509 20510 20511 20512 20513 20514 20515 20516 20517 20518 20519 20520 20521 20522 20523 20524 20525 20526 20527 20528 20529 20530 20531 20532 20533 20534 20535 20536 20537 20538 20539 20540 20541 20542 20543 20544 20545 20546 20547 20548 20549 20550 20551 20552 20553 20554 20555 20556 20557 20558 20559 20560 20561 20562 20563 20564 20565 20566 20567 20568 20569 20570 20571 20572 20573 20574 20575 20576 20577 20578 20579 20580 20581 20582 20583 20584 20585 20586 20587 20588 20589 20590 20591 20592 20593 20594 20595 20596 20597 20598 20599 20600 20601 20602 20603 20604 20605 20606 20607 20608 20609 20610 20611 20612 20613 20614 20615 20616 20617 20618 20619 20620 20621 20622 20623 20624 20625 20626 20627 20628 20629 20630 20631 20632 20633 20634 20635 20636 20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649 20650 20651 20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692 20693 20694 20695 20696 20697 20698 20699 20700 20701 20702 20703 20704 20705 20706 20707 20708 20709 20710 20711 20712 20713 20714 20715 20716 20717 20718 20719 20720 20721 20722 20723 20724 20725 20726 20727 20728 20729 20730 20731 20732 20733 20734 20735 20736 20737 20738 20739 20740 20741 20742 20743 20744 20745 20746 20747 20748 20749 20750 20751 20752 20753 20754 20755 20756 20757 20758 20759 20760 20761 20762 20763 20764 20765 20766 20767 20768 20769 20770 20771 20772 20773 20774 20775 20776 20777 20778 20779 20780 20781 20782 20783 20784 20785 20786 20787 20788 20789 20790 20791 20792 20793 20794 20795 20796 20797 20798 20799 20800 20801 20802 20803 20804 20805 20806 20807 20808 20809 20810 20811 20812 20813 20814 20815 20816 20817 20818 20819 20820 20821 20822 20823 20824 20825 20826 20827 20828 20829 20830 20831 20832 20833 20834 20835 20836 20837 20838 20839 20840 20841 20842 20843 20844 20845 20846 20847 20848 20849 20850 20851 20852 20853 20854 20855 20856 20857 20858 20859 20860 20861 20862 20863 20864 20865 20866 20867 20868 20869 20870 20871 20872 20873 20874 20875 20876 20877 20878 20879 20880 20881 20882 20883 20884 20885 20886 20887 20888 20889 20890 20891 20892 20893 20894 20895 20896 20897 20898 20899 20900 20901 20902 20903 20904 20905 20906 20907 20908 20909 20910 20911 20912 20913 20914 20915 20916 20917 20918 20919 20920 20921 20922 20923 20924 20925 20926 20927 20928 20929 20930 20931 20932 20933 20934 20935 20936 20937 20938 20939 20940 20941 20942 20943 20944 20945 20946 20947 20948 20949 20950 20951 20952 20953 20954 20955 20956 20957 20958 20959 20960 20961 20962 20963 20964 20965 20966 20967 20968 20969 20970 20971 20972 20973 20974 20975 20976 20977 20978 20979 20980 20981 20982 20983 20984 20985 20986 20987 20988 20989 20990 20991 20992 20993 20994 20995 20996 20997 20998 20999 21000 21001 21002 21003 21004 21005 21006 21007 21008 21009 21010 21011 21012 21013 21014 21015 21016 21017 21018 21019 21020 21021 21022 21023 21024 21025 21026 21027 21028 21029 21030 21031 21032 21033 21034 21035 21036 21037 21038 21039 21040 21041 21042 21043 21044 21045 21046 21047 21048 21049 21050 21051 21052 21053 21054 21055 21056 21057 21058 21059 21060 21061 21062 21063 21064 21065 21066 21067 21068 21069 21070 21071 21072 21073 21074 21075 21076 21077 21078 21079 21080 21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091 21092 21093 21094 21095 21096 21097 21098 21099 21100 21101 21102 21103 21104 21105 21106 21107 21108 21109 21110 21111 21112 21113 21114 21115 21116 21117 21118 21119 21120 21121 21122 21123 21124 21125 21126 21127 21128 21129 21130 21131 21132 21133 21134 21135 21136 21137 21138 21139 21140 21141 21142 21143 21144 21145 21146 21147 21148 21149 21150 21151 21152 21153 21154 21155 21156 21157 21158 21159 21160 21161 21162 21163 21164 21165 21166 21167 21168 21169 21170 21171 21172 21173 21174 21175 21176 21177 21178 21179 21180 21181 21182 21183 21184 21185 21186 21187 21188 21189 21190 21191 21192 21193 21194 21195 21196 21197 21198 21199 21200 21201 21202 21203 21204 21205 21206 21207 21208 21209 21210 21211 21212 21213 21214 21215 21216 21217 21218 21219 21220 21221 21222 21223 21224 21225 21226 21227 21228 21229 21230 21231 21232 21233 21234 21235 21236 21237 21238 21239 21240 21241 21242 21243 21244 21245 21246 21247 21248 21249 21250 21251 21252 21253 21254 21255 21256 21257 21258 21259 21260 21261 21262 21263 21264 21265 21266 21267 21268 21269 21270 21271 21272 21273 21274 21275 21276 21277 21278 21279 21280 21281 21282 21283 21284 21285 21286 21287 21288 21289 21290 21291 21292 21293 21294 21295 21296 21297 21298 21299 21300 21301 21302 21303 21304 21305 21306 21307 21308 21309 21310 21311 21312 21313 21314 21315 21316 21317 21318 21319 21320 21321 21322 21323 21324 21325 21326 21327 21328 21329 21330 21331 21332 21333 21334 21335 21336 21337 21338 21339 21340 21341 21342 21343 21344 21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355 21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379 21380 21381 21382 21383 21384 21385 21386 21387 21388 21389 21390 21391 21392 21393 21394 21395 21396 21397 21398 21399 21400 21401 21402 21403 21404 21405 21406 21407 21408 21409 21410 21411 21412 21413 21414 21415 21416 21417 21418 21419 21420 21421 21422 21423 21424 21425 21426 21427 21428 21429 21430 21431 21432 21433 21434 21435 21436 21437 21438 21439 21440 21441 21442 21443 21444 21445 21446 21447 21448 21449 21450 21451 21452 21453 21454 21455 21456 21457 21458 21459 21460 21461 21462 21463 21464 21465 21466 21467 21468 21469 21470 21471 21472 21473 21474 21475 21476 21477 21478 21479 21480 21481 21482 21483 21484 21485 21486 21487 21488 21489 21490 21491 21492 21493 21494 21495 21496 21497 21498 21499 21500 21501 21502 21503 21504 21505 21506 21507 21508 21509 21510 21511 21512 21513 21514 21515 21516 21517 21518 21519 21520 21521 21522 21523 21524 21525 21526 21527 21528 21529 21530 21531 21532 21533 21534 21535 21536 21537 21538 21539 21540 21541 21542 21543 21544 21545 21546 21547 21548 21549 21550 21551 21552 21553 21554 21555 21556 21557 21558 21559 21560 21561 21562 21563 21564 21565 21566 21567 21568 21569 21570 21571 21572 21573 21574 21575 21576 21577 21578 21579 21580 21581 21582 21583 21584 21585 21586 21587 21588 21589 21590 21591 21592 21593 21594 21595 21596 21597 21598 21599 21600 21601 21602 21603 21604 21605 21606 21607 21608 21609 21610 21611 21612 21613 21614 21615 21616 21617 21618 21619 21620 21621 21622 21623 21624 21625 21626 21627 21628 21629 21630 21631 21632 21633 21634 21635 21636 21637 21638 21639 21640 21641 21642 21643 21644 21645 21646 21647 21648 21649 21650 21651 21652 21653 21654 21655 21656 21657 21658 21659 21660 21661 21662 21663 21664 21665 21666 21667 21668 21669 21670 21671 21672 21673 21674 21675 21676 21677 21678 21679 21680 21681 21682 21683 21684 21685 21686 21687 21688 21689 21690 21691 21692 21693 21694 21695 21696 21697 21698 21699 21700 21701 21702 21703 21704 21705 21706 21707 21708 21709 21710 21711 21712 21713 21714 21715 21716 21717 21718 21719 21720 21721 21722 21723 21724 21725 21726 21727 21728 21729 21730 21731 21732 21733 21734 21735 21736 21737 21738 21739 21740 21741 21742 21743 21744 21745 21746 21747 21748 21749 21750 21751 21752 21753 21754 21755 21756 21757 21758 21759 21760 21761 21762 21763 21764 21765 21766 21767 21768 21769 21770 21771 21772 21773 21774 21775 21776 21777 21778 21779 21780 21781 21782 21783 21784 21785 21786 21787 21788 21789 21790 21791 21792 21793 21794 21795 21796 21797 21798 21799 21800 21801 21802 21803 21804 21805 21806 21807 21808 21809 21810 21811 21812 21813 21814 21815 21816 21817 21818 21819 21820 21821 21822 21823 21824 21825 21826 21827 21828 21829 21830 21831 21832 21833 21834 21835 21836 21837 21838 21839 21840 21841 21842 21843 21844 21845 21846 21847 21848 21849 21850 21851 21852 21853 21854 21855 21856 21857 21858 21859 21860 21861 21862 21863 21864 21865 21866 21867 21868 21869 21870 21871 21872 21873 21874 21875 21876 21877 21878 21879 21880 21881 21882 21883 21884 21885 21886 21887 21888 21889 21890 21891 21892 21893 21894 21895 21896 21897 21898 21899 21900 21901 21902 21903 21904 21905 21906 21907 21908 21909 21910 21911 21912 21913 21914 21915 21916 21917 21918 21919 21920 21921 21922 21923 21924 21925 21926 21927 21928 21929 21930 21931 21932 21933 21934 21935 21936 21937 21938 21939 21940 21941 21942 21943 21944 21945 21946 21947 21948 21949 21950 21951 21952 21953 21954 21955 21956 21957 21958 21959 21960 21961 21962 21963 21964 21965 21966 21967 21968 21969 21970 21971 21972 21973 21974 21975 21976 21977 21978 21979 21980 21981 21982 21983 21984 21985 21986 21987 21988 21989 21990 21991 21992 21993 21994 21995 21996 21997 21998 21999 22000 22001 22002 22003 22004 22005 22006 22007 22008 22009 22010 22011 22012 22013 22014 22015 22016 22017 22018 22019 22020 22021 22022 22023 22024 22025 22026 22027 22028 22029 22030 22031 22032 22033 22034 22035 22036 22037 22038 22039 22040 22041 22042 22043 22044 22045 22046 22047 22048 22049 22050 22051 22052 22053 22054 22055 22056 22057 22058 22059 22060 22061 22062 22063 22064 22065 22066 22067 22068 22069 22070 22071 22072 22073 22074 22075 22076 22077 22078 22079 22080 22081 22082 22083 22084 22085 22086 22087 22088 22089 22090 22091 22092 22093 22094 22095 22096 22097 22098 22099 22100 22101 22102 22103 22104 22105 22106 22107 22108 22109 22110 22111 22112 22113 22114 22115 22116 22117 22118 22119 22120 22121 22122 22123 22124 22125 22126 22127 22128 22129 22130 22131 22132 22133 22134 22135 22136 22137 22138 22139 22140 22141 22142 22143 22144 22145 22146 22147 22148 22149 22150 22151 22152 22153 22154 22155 22156 22157 22158 22159 22160 22161 22162 22163 22164 22165 22166 22167 22168 22169 22170 22171 22172 22173 22174 22175 22176 22177 22178 22179 22180 22181 22182 22183 22184 22185 22186 22187 22188 22189 22190 22191 22192 22193 22194 22195 22196 22197 22198 22199 22200 22201 22202 22203 22204 22205 22206 22207 22208 22209 22210 22211 22212 22213 22214 22215 22216 22217 22218 22219 22220 22221 22222 22223 22224 22225 22226 22227 22228 22229 22230 22231 22232 22233 22234 22235 22236 22237 22238 22239 22240 22241 22242 22243 22244 22245 22246 22247 22248 22249 22250 22251 22252 22253 22254 22255 22256 22257 22258 22259 22260 22261 22262 22263 22264 22265 22266 22267 22268 22269 22270 22271 22272 22273 22274 22275 22276 22277 22278 22279 22280 22281 22282 22283 22284 22285 22286 22287 22288 22289 22290 22291 22292 22293 22294 22295 22296 22297 22298 22299 22300 22301 22302 22303 22304 22305 22306 22307 22308 22309 22310 22311 22312 22313 22314 22315 22316 22317 22318 22319 22320 22321 22322 22323 22324 22325 22326 22327 22328 22329 22330 22331 22332 22333 22334 22335 22336 22337 22338 22339 22340 22341 22342 22343 22344 22345 22346 22347 22348 22349 22350 22351 22352 22353 22354 22355 22356 22357 22358 22359 22360 22361 22362 22363 22364 22365 22366 22367 22368 22369 22370 22371 22372 22373 22374 22375 22376 22377 22378 22379 22380 22381 22382 22383 22384 22385 22386 22387 22388 22389 22390 22391 22392 22393 22394 22395 22396 22397 22398 22399 22400 22401 22402 22403 22404 22405 22406 22407 22408 22409 22410 22411 22412 22413 22414 22415 22416 22417 22418 22419 22420 22421 22422 22423 22424 22425 22426 22427 22428 22429 22430 22431 22432 22433 22434 22435 22436 22437 22438 22439 22440 22441 22442 22443 22444 22445 22446 22447 22448 22449 22450 22451 22452 22453 22454 22455 22456 22457 22458 22459 22460 22461 22462 22463 22464 22465 22466 22467 22468 22469 22470 22471 22472 22473 22474 22475 22476 22477 22478 22479 22480 22481 22482 22483 22484 22485 22486 22487 22488 22489 22490 22491 22492 22493 22494 22495 22496 22497 22498 22499 22500 22501 22502 22503 22504 22505 22506 22507 22508 22509 22510 22511 22512 22513 22514 22515 22516 22517 22518 22519 22520 22521 22522 22523 22524 22525 22526 22527 22528 22529 22530 22531 22532 22533 22534 22535 22536 22537 22538 22539 22540 22541 22542 22543 22544 22545 22546 22547 22548 22549 22550 22551 22552 22553 22554 22555 22556 22557 22558 22559 22560 22561 22562 22563 22564 22565 22566 22567 22568 22569 22570 22571 22572 22573 22574 22575 22576 22577 22578 22579 22580 22581 22582 22583 22584 22585 22586 22587 22588 22589 22590 22591 22592 22593 22594 22595 22596 22597 22598 22599 22600 22601 22602 22603 22604 22605 22606 22607 22608 22609 22610 22611 22612 22613 22614 22615 22616 22617 22618 22619 22620 22621 22622 22623 22624 22625 22626 22627 22628 22629 22630 22631 22632 22633 22634 22635 22636 22637 22638 22639 22640 22641 22642 22643 22644 22645 22646 22647 22648 22649 22650 22651 22652 22653 22654 22655 22656 22657 22658 22659 22660 22661 22662 22663 22664 22665 22666 22667 22668 22669 22670 22671 22672 22673 22674 22675 22676 22677 22678 22679 22680 22681 22682 22683 22684 22685 22686 22687 22688 22689 22690 22691 22692 22693 22694 22695 22696 22697 22698 22699 22700 22701 22702 22703 22704 22705 22706 22707 22708 22709 22710 22711 22712 22713 22714 22715 22716 22717 22718 22719 22720 22721 22722 22723 22724 22725 22726 22727 22728 22729 22730 22731 22732 22733 22734 22735 22736 22737 22738 22739 22740 22741 22742 22743 22744 22745 22746 22747 22748 22749 22750 22751 22752 22753 22754 22755 22756 22757 22758 22759 22760 22761 22762 22763 22764 22765 22766 22767 22768 22769 22770 22771 22772 22773 22774 22775 22776 22777 22778 22779 22780 22781 22782 22783 22784 22785 22786 22787 22788 22789 22790 22791 22792 22793 22794 22795 22796 22797 22798 22799 22800 22801 22802 22803 22804 22805 22806 22807 22808 22809 22810 22811 22812 22813 22814 22815 22816 22817 22818 22819 22820 22821 22822 22823 22824 22825 22826 22827 22828 22829 22830 22831 22832 22833 22834 22835 22836 22837 22838 22839 22840 22841 22842 22843 22844 22845 22846 22847 22848 22849 22850 22851 22852 22853 22854 22855 22856 22857 22858 22859 22860 22861 22862 22863 22864 22865 22866 22867 22868 22869 22870 22871 22872 22873 22874 22875 22876 22877 22878 22879 22880 22881 22882 22883 22884 22885 22886 22887 22888 22889 22890 22891 22892 22893 22894 22895 22896 22897 22898 22899 22900 22901 22902 22903 22904 22905 22906 22907 22908 22909 22910 22911 22912 22913 22914 22915 22916 22917 22918 22919 22920 22921 22922 22923 22924 22925 22926 22927 22928 22929 22930 22931 22932 22933 22934 22935 22936 22937 22938 22939 22940 22941 22942 22943 22944 22945 22946 22947 22948 22949 22950 22951 22952 22953 22954 22955 22956 22957 22958 22959 22960 22961 22962 22963 22964 22965 22966 22967 22968 22969 22970 22971 22972 22973 22974 22975 22976 22977 22978 22979 22980 22981 22982 22983 22984 22985 22986 22987 22988 22989 22990 22991 22992 22993 22994 22995 22996 22997 22998 22999 23000 23001 23002 23003 23004 23005 23006 23007 23008 23009 23010 23011 23012 23013 23014 23015 23016 23017 23018 23019 23020 23021 23022 23023 23024 23025 23026 23027 23028 23029 23030 23031 23032 23033 23034 23035 23036 23037 23038 23039 23040 23041 23042 23043 23044 23045 23046 23047 23048 23049 23050 23051 23052 23053 23054 23055 23056 23057 23058 23059 23060 23061 23062 23063 23064 23065 23066 23067 23068 23069 23070 23071 23072 23073 23074 23075 23076 23077 23078 23079 23080 23081 23082 23083 23084 23085 23086 23087 23088 23089 23090 23091 23092 23093 23094 23095 23096 23097 23098 23099 23100 23101 23102 23103 23104 23105 23106 23107 23108 23109 23110 23111 23112 23113 23114 23115 23116 23117 23118 23119 23120 23121 23122 23123 23124 23125 23126 23127 23128 23129 23130 23131 23132 23133 23134 23135 23136 23137 23138 23139 23140 23141 23142 23143 23144 23145 23146 23147 23148 23149 23150 23151 23152 23153 23154 23155 23156 23157 23158 23159 23160 23161 23162 23163 23164 23165 23166 23167 23168 23169 23170 23171 23172 23173 23174 23175 23176 23177 23178 23179 23180 23181 23182 23183 23184 23185 23186 23187 23188 23189 23190 23191 23192 23193 23194 23195 23196 23197 23198 23199 23200 23201 23202 23203 23204 23205 23206 23207 23208 23209 23210 23211 23212 23213 23214 23215 23216 23217 23218 23219 23220 23221 23222 23223 23224 23225 23226 23227 23228 23229 23230 23231 23232 23233 23234 23235 23236 23237 23238 23239 23240 23241 23242 23243 23244 23245 23246 23247 23248 23249 23250 23251 23252 23253 23254 23255 23256 23257 23258 23259 23260 23261 23262 23263 23264 23265 23266 23267 23268 23269 23270 23271 23272 23273 23274 23275 23276 23277 23278 23279 23280 23281 23282 23283 23284 23285 23286 23287 23288 23289 23290 23291 23292 23293 23294 23295 23296 23297 23298 23299 23300 23301 23302 23303 23304 23305 23306 23307 23308 23309 23310 23311 23312 23313 23314 23315 23316 23317 23318 23319 23320 23321 23322 23323 23324 23325 23326 23327 23328 23329 23330 23331 23332 23333 23334 23335 23336 23337 23338 23339 23340 23341 23342 23343 23344 23345 23346 23347 23348 23349 23350 23351 23352 23353 23354 23355 23356 23357 23358 23359 23360 23361 23362 23363 23364 23365 23366 23367 23368 23369 23370 23371 23372 23373 23374 23375 23376 23377 23378 23379 23380 23381 23382 23383 23384 23385 23386 23387 23388 23389 23390 23391 23392 23393 23394 23395 23396 23397 23398 23399 23400 23401 23402 23403 23404 23405 23406 23407 23408 23409 23410 23411 23412 23413 23414 23415 23416 23417 23418 23419 23420 23421 23422 23423 23424 23425 23426 23427 23428 23429 23430 23431 23432 23433 23434 23435 23436 23437 23438 23439 23440 23441 23442 23443 23444 23445 23446 23447 23448 23449 23450 23451 23452 23453 23454 23455 23456 23457 23458 23459 23460 23461 23462 23463 23464 23465 23466 23467 23468 23469 23470 23471 23472 23473 23474 23475 23476 23477 23478 23479 23480 23481 23482 23483 23484 23485 23486 23487 23488 23489 23490 23491 23492 23493 23494 23495 23496 23497 23498 23499 23500 23501 23502 23503 23504 23505 23506 23507 23508 23509 23510 23511 23512 23513 23514 23515 23516 23517 23518 23519 23520 23521 23522 23523 23524 23525 23526 23527 23528 23529 23530 23531 23532 23533 23534 23535 23536 23537 23538 23539 23540 23541 23542 23543 23544 23545 23546 23547 23548 23549 23550 23551 23552 23553 23554 23555 23556 23557 23558 23559 23560 23561 23562 23563 23564 23565 23566 23567 23568 23569 23570 23571 23572 23573 23574 23575 23576 23577 23578 23579 23580 23581 23582 23583 23584 23585 23586 23587 23588 23589 23590 23591 23592 23593 23594 23595 23596 23597 23598 23599 23600 23601 23602 23603 23604 23605 23606 23607 23608 23609 23610 23611 23612 23613 23614 23615 23616 23617 23618 23619 23620 23621 23622 23623 23624 23625 23626 23627 23628 23629 23630 23631 23632 23633 23634 23635 23636 23637 23638 23639 23640 23641 23642 23643 23644 23645 23646 23647 23648 23649 23650 23651 23652 23653 23654 23655 23656 23657 23658 23659 23660 23661 23662 23663 23664 23665 23666 23667 23668 23669 23670 23671 23672 23673 23674 23675 23676 23677 23678 23679 23680 23681 23682 23683 23684 23685 23686 23687 23688 23689 23690 23691 23692 23693 23694 23695 23696 23697 23698 23699 23700 23701 23702 23703 23704 23705 23706 23707 23708 23709 23710 23711 23712 23713 23714 23715 23716 23717 23718 23719 23720 23721 23722 23723 23724 23725 23726 23727 23728 23729 23730 23731 23732 23733 23734 23735 23736 23737 23738 23739 23740 23741 23742 23743 23744 23745 23746 23747 23748 23749 23750 23751 23752 23753 23754 23755 23756 23757 23758 23759 23760 23761 23762 23763 23764 23765 23766 23767 23768 23769 23770 23771 23772 23773 23774 23775 23776 23777 23778 23779 23780 23781 23782 23783 23784 23785 23786 23787 23788 23789 23790 23791 23792 23793 23794 23795 23796 23797 23798 23799 23800 23801 23802 23803 23804 23805 23806 23807 23808 23809 23810 23811 23812 23813 23814 23815 23816 23817 23818 23819 23820 23821 23822 23823 23824 23825 23826 23827 23828 23829 23830 23831 23832 23833 23834 23835 23836 23837 23838 23839 23840 23841 23842 23843 23844 23845 23846 23847 23848 23849 23850 23851 23852 23853 23854 23855 23856 23857 23858 23859 23860 23861 23862 23863 23864 23865 23866 23867 23868 23869 23870 23871 23872 23873 23874 23875 23876 23877 23878 23879 23880 23881 23882 23883 23884 23885 23886 23887 23888 23889 23890 23891 23892 23893 23894 23895 23896 23897 23898 23899 23900 23901 23902 23903 23904 23905 23906 23907 23908 23909 23910 23911 23912 23913 23914 23915 23916 23917 23918 23919 23920 23921 23922 23923 23924 23925 23926 23927 23928 23929 23930 23931 23932 23933 23934 23935 23936 23937 23938 23939 23940 23941 23942 23943 23944 23945 23946 23947 23948 23949 23950 23951 23952 23953 23954 23955 23956 23957 23958 23959 23960 23961 23962 23963 23964 23965 23966 23967 23968 23969 23970 23971 23972 23973 23974 23975 23976 23977 23978 23979 23980 23981 23982 23983 23984 23985 23986 23987 23988 23989 23990 23991 23992 23993 23994 23995 23996 23997 23998 23999 24000 24001 24002 24003 24004 24005 24006 24007 24008 24009 24010 24011 24012 24013 24014 24015 24016 24017 24018 24019 24020 24021 24022 24023 24024 24025 24026 24027 24028 24029 24030 24031 24032 24033 24034 24035 24036 24037 24038 24039 24040 24041 24042 24043 24044 24045 24046 24047 24048 24049 24050 24051 24052 24053 24054 24055 24056 24057 24058 24059 24060 24061 24062 24063 24064 24065 24066 24067 24068 24069 24070 24071 24072 24073 24074 24075 24076 24077 24078 24079 24080 24081 24082 24083 24084 24085 24086 24087 24088 24089 24090 24091 24092 24093 24094 24095 24096 24097 24098 24099 24100 24101 24102 24103 24104 24105 24106 24107 24108 24109 24110 24111 24112 24113 24114 24115 24116 24117 24118 24119 24120 24121 24122 24123 24124 24125 24126 24127 24128 24129 24130 24131 24132 24133 24134 24135 24136 24137 24138 24139 24140 24141 24142 24143 24144 24145 24146 24147 24148 24149 24150 24151 24152 24153 24154 24155 24156 24157 24158 24159 24160 24161 24162 24163 24164 24165 24166 24167 24168 24169 24170 24171 24172 24173 24174 24175 24176 24177 24178 24179 24180 24181 24182 24183 24184 24185 24186 24187 24188 24189 24190 24191 24192 24193 24194 24195 24196 24197 24198 24199 24200 24201 24202 24203 24204 24205 24206 24207 24208 24209 24210 24211 24212 24213 24214 24215 24216 24217 24218 24219 24220 24221 24222 24223 24224 24225 24226 24227 24228 24229 24230 24231 24232 24233 24234 24235 24236 24237 24238 24239 24240 24241 24242 24243 24244 24245 24246 24247 24248 24249 24250 24251 24252 24253 24254 24255 24256 24257 24258 24259 24260 24261 24262 24263 24264 24265 24266 24267 24268 24269 24270 24271 24272 24273 24274 24275 24276 24277 24278 24279 24280 24281 24282 24283 24284 24285 24286 24287 24288 24289 24290 24291 24292 24293 24294 24295 24296 24297 24298 24299 24300 24301 24302 24303 24304 24305 24306 24307 24308 24309 24310 24311 24312 24313 24314 24315 24316 24317 24318 24319 24320 24321 24322 24323 24324 24325 24326 24327 24328 24329 24330 24331 24332 24333 24334 24335 24336 24337 24338 24339 24340 24341 24342 24343 24344 24345 24346 24347 24348 24349 24350 24351 24352 24353 24354 24355 24356 24357 24358 24359 24360 24361 24362 24363 24364 24365 24366 24367 24368 24369 24370 24371 24372 24373 24374 24375 24376 24377 24378 24379 24380 24381 24382 24383 24384 24385 24386 24387 24388 24389 24390 24391 24392 24393 24394 24395 24396 24397 24398 24399 24400 24401 24402 24403 24404 24405 24406 24407 24408 24409 24410 24411 24412 24413 24414 24415 24416 24417 24418 24419 24420 24421 24422 24423 24424 24425 24426 24427 24428 24429 24430 24431 24432 24433 24434 24435 24436 24437 24438 24439 24440 24441 24442 24443 24444 24445 24446 24447 24448 24449 24450 24451 24452 24453 24454 24455 24456 24457 24458 24459 24460 24461 24462 24463 24464 24465 24466 24467 24468 24469 24470 24471 24472 24473 24474 24475 24476 24477 24478 24479 24480 24481 24482 24483 24484 24485 24486 24487 24488 24489 24490 24491 24492 24493 24494 24495 24496 24497 24498 24499 24500 24501 24502 24503 24504 24505 24506 24507 24508 24509 24510 24511 24512 24513 24514 24515 24516 24517 24518 24519 24520 24521 24522 24523 24524 24525 24526 24527 24528 24529 24530 24531 24532 24533 24534 24535 24536 24537 24538 24539 24540 24541 24542 24543 24544 24545 24546 24547 24548 24549 24550 24551 24552 24553 24554 24555 24556 24557 24558 24559 24560 24561 24562 24563 24564 24565 24566 24567 24568 24569 24570 24571 24572 24573 24574 24575 24576 24577 24578 24579 24580 24581 24582 24583 24584 24585 24586 24587 24588 24589 24590 24591 24592 24593 24594 24595 24596 24597 24598 24599 24600 24601 24602 24603 24604 24605 24606 24607 24608 24609 24610 24611 24612 24613 24614 24615 24616 24617 24618 24619 24620 24621 24622 24623 24624 24625 24626 24627 24628 24629 24630 24631 24632 24633 24634 24635 24636 24637 24638 24639 24640 24641 24642 24643 24644 24645 24646 24647 24648 24649 24650 24651 24652 24653 24654 24655 24656 24657 24658 24659 24660 24661 24662 24663 24664 24665 24666 24667 24668 24669 24670 24671 24672 24673 24674 24675 24676 24677 24678 24679 24680 24681 24682 24683 24684 24685 24686 24687 24688 24689 24690 24691 24692 24693 24694 24695 24696 24697 24698 24699 24700 24701 24702 24703 24704 24705 24706 24707 24708 24709 24710 24711 24712 24713 24714 24715 24716 24717 24718 24719 24720 24721 24722 24723 24724 24725 24726 24727 24728 24729 24730 24731 24732 24733 24734 24735 24736 24737 24738 24739 24740 24741 24742 24743 24744 24745 24746 24747 24748 24749 24750 24751 24752 24753 24754 24755 24756 24757 24758 24759 24760 24761 24762 24763 24764 24765 24766 24767 24768 24769 24770 24771 24772 24773 24774 24775 24776 24777 24778 24779 24780 24781 24782 24783 24784 24785 24786 24787 24788 24789 24790 24791 24792 24793 24794 24795 24796 24797 24798 24799 24800 24801 24802 24803 24804 24805 24806 24807 24808 24809 24810 24811 24812 24813 24814 24815 24816 24817 24818 24819 24820 24821 24822 24823 24824 24825 24826 24827 24828 24829 24830 24831 24832 24833 24834 24835 24836 24837 24838 24839 24840 24841 24842 24843 24844 24845 24846 24847 24848 24849 24850 24851 24852 24853 24854 24855 24856 24857 24858 24859 24860 24861 24862 24863 24864 24865 24866 24867 24868 24869 24870 24871 24872 24873 24874 24875 24876 24877 24878 24879 24880 24881 24882 24883 24884 24885 24886 24887 24888 24889 24890 24891 24892 24893 24894 24895 24896 24897 24898 24899 24900 24901 24902 24903 24904 24905 24906 24907 24908 24909 24910 24911 24912 24913 24914 24915 24916 24917 24918 24919 24920 24921 24922 24923 24924 24925 24926 24927 24928 24929 24930 24931 24932 24933 24934 24935 24936 24937 24938 24939 24940 24941 24942 24943 24944 24945 24946 24947 24948 24949 24950 24951 24952 24953 24954 24955 24956 24957 24958 24959 24960 24961 24962 24963 24964 24965 24966 24967 24968 24969 24970 24971 24972 24973 24974 24975 24976 24977 24978 24979 24980 24981 24982 24983 24984 24985 24986 24987 24988 24989 24990 24991 24992 24993 24994 24995 24996 24997 24998 24999 25000 25001 25002 25003 25004 25005 25006 25007 25008 25009 25010 25011 25012 25013 25014 25015 25016 25017 25018 25019 25020 25021 25022 25023 25024 25025 25026 25027 25028 25029 25030 25031 25032 25033 25034 25035 25036 25037 25038 25039 25040 25041 25042 25043 25044 25045 25046 25047 25048 25049 25050 25051 25052 25053 25054 25055 25056 25057 25058 25059 25060 25061 25062 25063 25064 25065 25066 25067 25068 25069 25070 25071 25072 25073 25074 25075 25076 25077 25078 25079 25080 25081 25082 25083 25084 25085 25086 25087 25088 25089 25090 25091 25092 25093 25094 25095 25096 25097 25098 25099 25100 25101 25102 25103 25104 25105 25106 25107 25108 25109 25110 25111 25112 25113 25114 25115 25116 25117 25118 25119 25120 25121 25122 25123 25124 25125 25126 25127 25128 25129 25130 25131 25132 25133 25134 25135 25136 25137 25138 25139 25140 25141 25142 25143 25144 25145 25146 25147 25148 25149 25150 25151 25152 25153 25154 25155 25156 25157 25158 25159 25160 25161 25162 25163 25164 25165 25166 25167 25168 25169 25170 25171 25172 25173 25174 25175 25176 25177 25178 25179 25180 25181 25182 25183 25184 25185 25186 25187 25188 25189 25190 25191 25192 25193 25194 25195 25196 25197 25198 25199 25200 25201 25202 25203 25204 25205 25206 25207 25208 25209 25210 25211 25212 25213 25214 25215 25216 25217 25218 25219 25220 25221 25222 25223 25224 25225 25226 25227 25228 25229 25230 25231 25232 25233 25234 25235 25236 25237 25238 25239 25240 25241 25242 25243 25244 25245 25246 25247 25248 25249 25250 25251 25252 25253 25254 25255 25256 25257 25258 25259 25260 25261 25262 25263 25264 25265 25266 25267 25268 25269 25270 25271 25272 25273 25274 25275 25276 25277 25278 25279 25280 25281 25282 25283 25284 25285 25286 25287 25288 25289 25290 25291 25292 25293 25294 25295 25296 25297 25298 25299 25300 25301 25302 25303 25304 25305 25306 25307 25308 25309 25310 25311 25312 25313 25314 25315 25316 25317 25318 25319 25320 25321 25322 25323 25324 25325 25326 25327 25328 25329 25330 25331 25332 25333 25334 25335 25336 25337 25338 25339 25340 25341 25342 25343 25344 25345 25346 25347 25348 25349 25350 25351 25352 25353 25354 25355 25356 25357 25358 25359 25360 25361 25362 25363 25364 25365 25366 25367 25368 25369 25370 25371 25372 25373 25374 25375 25376 25377 25378 25379 25380 25381 25382 25383 25384 25385 25386 25387 25388 25389 25390 25391 25392 25393 25394 25395 25396 25397 25398 25399 25400 25401 25402 25403 25404 25405 25406 25407 25408 25409 25410 25411 25412 25413 25414 25415 25416 25417 25418 25419 25420 25421 25422 25423 25424 25425 25426 25427 25428 25429 25430 25431 25432 25433 25434 25435 25436 25437 25438 25439 25440 25441 25442 25443 25444 25445 25446 25447 25448 25449 25450 25451 25452 25453 25454 25455 25456 25457 25458 25459 25460 25461 25462 25463 25464 25465 25466 25467 25468 25469 25470 25471 25472 25473 25474 25475 25476 25477 25478 25479 25480 25481 25482 25483 25484 25485 25486 25487 25488 25489 25490 25491 25492 25493 25494 25495 25496 25497 25498 25499 25500 25501 25502 25503 25504 25505 25506 25507 25508 25509 25510 25511 25512 25513 25514 25515 25516 25517 25518 25519 25520 25521 25522 25523 25524 25525 25526 25527 25528 25529 25530 25531 25532 25533 25534 25535 25536 25537 25538 25539 25540 25541 25542 25543 25544 25545 25546 25547 25548 25549 25550 25551 25552 25553 25554 25555 25556 25557 25558 25559 25560 25561 25562 25563 25564 25565 25566 25567 25568 25569 25570 25571 25572 25573 25574 25575 25576 25577 25578 25579 25580 25581 25582 25583 25584 25585 25586 25587 25588 25589 25590 25591 25592 25593 25594 25595 25596 25597 25598 25599 25600 25601 25602 25603 25604 25605 25606 25607 25608 25609 25610 25611 25612 25613 25614 25615 25616 25617 25618 25619 25620 25621 25622 25623 25624 25625 25626 25627 25628 25629 25630 25631 25632 25633 25634 25635 25636 25637 25638 25639 25640 25641 25642 25643 25644 25645 25646 25647 25648 25649 25650 25651 25652 25653 25654 25655 25656 25657 25658 25659 25660 25661 25662 25663 25664 25665 25666 25667 25668 25669 25670 25671 25672 25673 25674 25675 25676 25677 25678 25679 25680 25681 25682 25683 25684 25685 25686 25687 25688 25689 25690 25691 25692 25693 25694 25695 25696 25697 25698 25699 25700 25701 25702 25703 25704 25705 25706 25707 25708 25709 25710 25711 25712 25713 25714 25715 25716 25717 25718 25719 25720 25721 25722 25723 25724 25725 25726 25727 25728 25729 25730 25731 25732 25733 25734 25735 25736 25737 25738 25739 25740 25741 25742 25743 25744 25745 25746 25747 25748 25749 25750 25751 25752 25753 25754 25755 25756 25757 25758 25759 25760 25761 25762 25763 25764 25765 25766 25767 25768 25769 25770 25771 25772 25773 25774 25775 25776 25777 25778 25779 25780 25781 25782 25783 25784 25785 25786 25787 25788 25789 25790 25791 25792 25793 25794 25795 25796 25797 25798 25799 25800 25801 25802 25803 25804 25805 25806 25807 25808 25809 25810 25811 25812 25813 25814 25815 25816 25817 25818 25819 25820 25821 25822 25823 25824 25825 25826 25827 25828 25829 25830 25831 25832 25833 25834 25835 25836 25837 25838 25839 25840 25841 25842 25843 25844 25845 25846 25847 25848 25849 25850 25851 25852 25853 25854 25855 25856 25857 25858 25859 25860 25861 25862 25863 25864 25865 25866 25867 25868 25869 25870 25871 25872 25873 25874 25875 25876 25877 25878 25879 25880 25881 25882 25883 25884 25885 25886 25887 25888 25889 25890 25891 25892 25893 25894 25895 25896 25897 25898 25899 25900 25901 25902 25903 25904 25905 25906 25907 25908 25909 25910 25911 25912 25913 25914 25915 25916 25917 25918 25919 25920 25921 25922 25923 25924 25925 25926 25927 25928 25929 25930 25931 25932 25933 25934 25935 25936 25937 25938 25939 25940 25941 25942 25943 25944 25945 25946 25947 25948 25949 25950 25951 25952 25953 25954 25955 25956 25957 25958 25959 25960 25961 25962 25963 25964 25965 25966 25967 25968 25969 25970 25971 25972 25973 25974 25975 25976 25977 25978 25979 25980 25981 25982 25983 25984 25985 25986 25987 25988 25989 25990 25991 25992 25993 25994 25995 25996 25997 25998 25999 26000 26001 26002 26003 26004 26005 26006 26007 26008 26009 26010 26011 26012 26013 26014 26015 26016 26017 26018 26019 26020 26021 26022 26023 26024 26025 26026 26027 26028 26029 26030 26031 26032 26033 26034 26035 26036 26037 26038 26039 26040 26041 26042 26043 26044 26045 26046 26047 26048 26049 26050 26051 26052 26053 26054 26055 26056 26057 26058 26059 26060 26061 26062 26063 26064 26065 26066 26067 26068 26069 26070 26071 26072 26073 26074 26075 26076 26077 26078 26079 26080 26081 26082 26083 26084 26085 26086 26087 26088 26089 26090 26091 26092 26093 26094 26095 26096 26097 26098 26099 26100 26101 26102 26103 26104 26105 26106 26107 26108 26109 26110 26111 26112 26113 26114 26115 26116 26117 26118 26119 26120 26121 26122 26123 26124 26125 26126 26127 26128 26129 26130 26131 26132 26133 26134 26135 26136 26137 26138 26139 26140 26141 26142 26143 26144 26145 26146 26147 26148 26149 26150 26151 26152 26153 26154 26155 26156 26157 26158 26159 26160 26161 26162 26163 26164 26165 26166 26167 26168 26169 26170 26171 26172 26173 26174 26175 26176 26177 26178 26179 26180 26181 26182 26183 26184 26185 26186 26187 26188 26189 26190 26191 26192 26193 26194 26195 26196 26197 26198 26199 26200 26201 26202 26203 26204 26205 26206 26207 26208 26209 26210 26211 26212 26213 26214 26215 26216 26217 26218 26219 26220 26221 26222 26223 26224 26225 26226 26227 26228 26229 26230 26231 26232 26233 26234 26235 26236 26237 26238 26239 26240 26241 26242 26243 26244 26245 26246 26247 26248 26249 26250 26251 26252 26253 26254 26255 26256 26257 26258 26259 26260 26261 26262 26263 26264 26265 26266 26267 26268 26269 26270 26271 26272 26273 26274 26275 26276 26277 26278 26279 26280 26281 26282 26283 26284 26285 26286 26287 26288 26289 26290 26291 26292 26293 26294 26295 26296 26297 26298 26299 26300 26301 26302 26303 26304 26305 26306 26307 26308 26309 26310 26311 26312 26313 26314 26315 26316 26317 26318 26319 26320 26321 26322 26323 26324 26325 26326 26327 26328 26329 26330 26331 26332 26333 26334 26335 26336 26337 26338 26339 26340 26341 26342 26343 26344 26345 26346 26347 26348 26349 26350 26351 26352 26353 26354 26355 26356 26357 26358 26359 26360 26361 26362 26363 26364 26365 26366 26367 26368 26369 26370 26371 26372 26373 26374 26375 26376 26377 26378 26379 26380 26381 26382 26383 26384 26385 26386 26387 26388 26389 26390 26391 26392 26393 26394 26395 26396 26397 26398 26399 26400 26401 26402 26403 26404 26405 26406 26407 26408 26409 26410 26411 26412 26413 26414 26415 26416 26417 26418 26419 26420 26421 26422 26423 26424 26425 26426 26427 26428 26429 26430 26431 26432 26433 26434 26435 26436 26437 26438 26439 26440 26441 26442 26443 26444 26445 26446 26447 26448 26449 26450 26451 26452 26453 26454 26455 26456 26457 26458 26459 26460 26461 26462 26463 26464 26465 26466 26467 26468 26469 26470 26471 26472 26473 26474 26475 26476 26477 26478 26479 26480 26481 26482 26483 26484 26485 26486 26487 26488 26489 26490 26491 26492 26493 26494 26495 26496 26497 26498 26499 26500 26501 26502 26503 26504 26505 26506 26507 26508 26509 26510 26511 26512 26513 26514 26515 26516 26517 26518 26519 26520 26521 26522 26523 26524 26525 26526 26527 26528 26529 26530 26531 26532 26533 26534 26535 26536 26537 26538 26539 26540 26541 26542 26543 26544 26545 26546 26547 26548 26549 26550 26551 26552 26553 26554 26555 26556 26557 26558 26559 26560 26561 26562 26563 26564 26565 26566 26567 26568 26569 26570 26571 26572 26573 26574 26575 26576 26577 26578 26579 26580 26581 26582 26583 26584 26585 26586 26587 26588 26589 26590 26591 26592 26593 26594 26595 26596 26597 26598 26599 26600 26601 26602 26603 26604 26605 26606 26607 26608 26609 26610 26611 26612 26613 26614 26615 26616 26617 26618 26619 26620 26621 26622 26623 26624 26625 26626 26627 26628 26629 26630 26631 26632 26633 26634 26635 26636 26637 26638 26639 26640 26641 26642 26643 26644 26645 26646 26647 26648 26649 26650 26651 26652 26653 26654 26655 26656 26657 26658 26659 26660 26661 26662 26663 26664 26665 26666 26667 26668 26669 26670 26671 26672 26673 26674 26675 26676 26677 26678 26679 26680 26681 26682 26683 26684 26685 26686 26687 26688 26689 26690 26691 26692 26693 26694 26695 26696 26697 26698 26699 26700 26701 26702 26703 26704 26705 26706 26707 26708 26709 26710 26711 26712 26713 26714 26715 26716 26717 26718 26719 26720 26721 26722 26723 26724 26725 26726 26727 26728 26729 26730 26731 26732 26733 26734 26735 26736 26737 26738 26739 26740 26741 26742 26743 26744 26745 26746 26747 26748 26749 26750 26751 26752 26753 26754 26755 26756 26757 26758 26759 26760 26761 26762 26763 26764 26765 26766 26767 26768 26769 26770 26771 26772 26773 26774 26775 26776 26777 26778 26779 26780 26781 26782 26783 26784 26785 26786 26787 26788 26789 26790 26791 26792 26793 26794 26795 26796 26797 26798 26799 26800 26801 26802 26803 26804 26805 26806 26807 26808 26809 26810 26811 26812 26813 26814 26815 26816 26817 26818 26819 26820 26821 26822 26823 26824 26825 26826 26827 26828 26829 26830 26831 26832 26833 26834 26835 26836 26837 26838 26839 26840 26841 26842 26843 26844 26845 26846 26847 26848 26849 26850 26851 26852 26853 26854 26855 26856 26857 26858 26859 26860 26861 26862 26863 26864 26865 26866 26867 26868 26869 26870 26871 26872 26873 26874 26875 26876 26877 26878 26879 26880 26881 26882 26883 26884 26885 26886 26887 26888 26889 26890 26891 26892 26893 26894 26895 26896 26897 26898 26899 26900 26901 26902 26903 26904 26905 26906 26907 26908 26909 26910 26911 26912 26913 26914 26915 26916 26917 26918 26919 26920 26921 26922 26923 26924 26925 26926 26927 26928 26929 26930 26931 26932 26933 26934 26935 26936 26937 26938 26939 26940 26941 26942 26943 26944 26945 26946 26947 26948 26949 26950 26951 26952 26953 26954 26955 26956 26957 26958 26959 26960 26961 26962 26963 26964 26965 26966 26967 26968 26969 26970 26971 26972 26973 26974 26975 26976 26977 26978 26979 26980 26981 26982 26983 26984 26985 26986 26987 26988 26989 26990 26991 26992 26993 26994 26995 26996 26997 26998 26999 27000 27001 27002 27003 27004 27005 27006 27007 27008 27009 27010 27011 27012 27013 27014 27015 27016 27017 27018 27019 27020 27021 27022 27023 27024 27025 27026 27027 27028 27029 27030 27031 27032 27033 27034 27035 27036 27037 27038 27039 27040 27041 27042 27043 27044 27045 27046 27047 27048 27049 27050 27051 27052 27053 27054 27055 27056 27057 27058 27059 27060 27061 27062 27063 27064 27065 27066 27067 27068 27069 27070 27071 27072 27073 27074 27075 27076 27077 27078 27079 27080 27081 27082 27083 27084 27085 27086 27087 27088 27089 27090 27091 27092 27093 27094 27095 27096 27097 27098 27099 27100 27101 27102 27103 27104 27105 27106 27107 27108 27109 27110 27111 27112 27113 27114 27115 27116 27117 27118 27119 27120 27121 27122 27123 27124 27125 27126 27127 27128 27129 27130 27131 27132 27133 27134 27135 27136 27137 27138 27139 27140 27141 27142 27143 27144 27145 27146 27147 27148 27149 27150 27151 27152 27153 27154 27155 27156 27157 27158 27159 27160 27161 27162 27163 27164 27165 27166 27167 27168 27169 27170 27171 27172 27173 27174 27175 27176 27177 27178 27179 27180 27181 27182 27183 27184 27185 27186 27187 27188 27189 27190 27191 27192 27193 27194 27195 27196 27197 27198 27199 27200 27201 27202 27203 27204 27205 27206 27207 27208 27209 27210 27211 27212 27213 27214 27215 27216 27217 27218 27219 27220 27221 27222 27223 27224 27225 27226 27227 27228 27229 27230 27231 27232 27233 27234 27235 27236 27237 27238 27239 27240 27241 27242 27243 27244 27245 27246 27247 27248 27249 27250 27251 27252 27253 27254 27255 27256 27257 27258 27259 27260 27261 27262 27263 27264 27265 27266 27267 27268 27269 27270 27271 27272 27273 27274 27275 27276 27277 27278 27279 27280 27281 27282 27283 27284 27285 27286 27287 27288 27289 27290 27291 27292 27293 27294 27295 27296 27297 27298 27299 27300 27301 27302 27303 27304 27305 27306 27307 27308 27309 27310 27311 27312 27313 27314 27315 27316 27317 27318 27319 27320 27321 27322 27323 27324 27325 27326 27327 27328 27329 27330 27331 27332 27333 27334 27335 27336 27337 27338 27339 27340 27341 27342 27343 27344 27345 27346 27347 27348 27349 27350 27351 27352 27353 27354 27355 27356 27357 27358 27359 27360 27361 27362 27363 27364 27365 27366 27367 27368 27369 27370 27371 27372 27373 27374 27375 27376 27377 27378 27379 27380 27381 27382 27383 27384 27385 27386 27387 27388 27389 27390 27391 27392 27393 27394 27395 27396 27397 27398 27399 27400 27401 27402 27403 27404 27405 27406 27407 27408 27409 27410 27411 27412 27413 27414 27415 27416 27417 27418 27419 27420 27421 27422 27423 27424 27425 27426 27427 27428 27429 27430 27431 27432 27433 27434 27435 27436 27437 27438 27439 27440 27441 27442 27443 27444 27445 27446 27447 27448 27449 27450 27451 27452 27453 27454 27455 27456 27457 27458 27459 27460 27461 27462 27463 27464 27465 27466 27467 27468 27469 27470 27471 27472 27473 27474 27475 27476 27477 27478 27479 27480 27481 27482 27483 27484 27485 27486 27487 27488 27489 27490 27491 27492 27493 27494 27495 27496 27497 27498 27499 27500 27501 27502 27503 27504 27505 27506 27507 27508 27509 27510 27511 27512 27513 27514 27515 27516 27517 27518 27519 27520 27521 27522 27523 27524 27525 27526 27527 27528 27529 27530 27531 27532 27533 27534 27535 27536 27537 27538 27539 27540 27541 27542 27543 27544 27545 27546 27547 27548 27549 27550 27551 27552 27553 27554 27555 27556 27557 27558 27559 27560 27561 27562 27563 27564 27565 27566 27567 27568 27569 27570 27571 27572 27573 27574 27575 27576 27577 27578 27579 27580 27581 27582 27583 27584 27585 27586 27587 27588 27589 27590 27591 27592 27593 27594 27595 27596 27597 27598 27599 27600 27601 27602 27603 27604 27605 27606 27607 27608 27609 27610 27611 27612 27613 27614 27615 27616 27617 27618 27619 27620 27621 27622 27623 27624 27625 27626 27627 27628 27629 27630 27631 27632 27633 27634 27635 27636 27637 27638 27639 27640 27641 27642 27643 27644 27645 27646 27647 27648 27649 27650 27651 27652 27653 27654 27655 27656 27657 27658 27659 27660 27661 27662 27663 27664 27665 27666 27667 27668 27669 27670 27671 27672 27673 27674 27675 27676 27677 27678 27679 27680 27681 27682 27683 27684 27685 27686 27687 27688 27689 27690 27691 27692 27693 27694 27695 27696 27697 27698 27699 27700 27701 27702 27703 27704 27705 27706 27707 27708 27709 27710 27711 27712 27713 27714 27715 27716 27717 27718 27719 27720 27721 27722 27723 27724 27725 27726 27727 27728 27729 27730 27731 27732 27733 27734 27735 27736 27737 27738 27739 27740 27741 27742 27743 27744 27745 27746 27747 27748 27749 27750 27751 27752 27753 27754 27755 27756 27757 27758 27759 27760 27761 27762 27763 27764 27765 27766 27767 27768 27769 27770 27771 27772 27773 27774 27775 27776 27777 27778 27779 27780 27781 27782 27783 27784 27785 27786 27787 27788 27789 27790 27791 27792 27793 27794 27795 27796 27797 27798 27799 27800 27801 27802 27803 27804 27805 27806 27807 27808 27809 27810 27811 27812 27813 27814 27815 27816 27817 27818 27819 27820 27821 27822 27823 27824 27825 27826 27827 27828 27829 27830 27831 27832 27833 27834 27835 27836 27837 27838 27839 27840 27841 27842 27843 27844 27845 27846 27847 27848 27849 27850 27851 27852 27853 27854 27855 27856 27857 27858 27859 27860 27861 27862 27863 27864 27865 27866 27867 27868 27869 27870 27871 27872 27873 27874 27875 27876 27877 27878 27879 27880 27881 27882 27883 27884 27885 27886 27887 27888 27889 27890 27891 27892 27893 27894 27895 27896 27897 27898 27899 27900 27901 27902 27903 27904 27905 27906 27907 27908 27909 27910 27911 27912 27913 27914 27915 27916 27917 27918 27919 27920 27921 27922 27923 27924 27925 27926 27927 27928 27929 27930 27931 27932 27933 27934 27935 27936 27937 27938 27939 27940 27941 27942 27943 27944 27945 27946 27947 27948 27949 27950 27951 27952 27953 27954 27955 27956 27957 27958 27959 27960 27961 27962 27963 27964 27965 27966 27967 27968 27969 27970 27971 27972 27973 27974 27975 27976 27977 27978 27979 27980 27981 27982 27983 27984 27985 27986 27987 27988 27989 27990 27991 27992 27993 27994 27995 27996 27997 27998 27999 28000 28001 28002 28003 28004 28005 28006 28007 28008 28009 28010 28011 28012 28013 28014 28015 28016 28017 28018 28019 28020 28021 28022 28023 28024 28025 28026 28027 28028 28029 28030 28031 28032 28033 28034 28035 28036 28037 28038 28039 28040 28041 28042 28043 28044 28045 28046 28047 28048 28049 28050 28051 28052 28053 28054 28055 28056 28057 28058 28059 28060 28061 28062 28063 28064 28065 28066 28067 28068 28069 28070 28071 28072 28073 28074 28075 28076 28077 28078 28079 28080 28081 28082 28083 28084 28085 28086 28087 28088 28089 28090 28091 28092 28093 28094 28095 28096 28097 28098 28099 28100 28101 28102 28103 28104 28105 28106 28107 28108 28109 28110 28111 28112 28113 28114 28115 28116 28117 28118 28119 28120 28121 28122 28123 28124 28125 28126 28127 28128 28129 28130 28131 28132 28133 28134 28135 28136 28137 28138 28139 28140 28141 28142 28143 28144 28145 28146 28147 28148 28149 28150 28151 28152 28153 28154 28155 28156 28157 28158 28159 28160 28161 28162 28163 28164 28165 28166 28167 28168 28169 28170 28171 28172 28173 28174 28175 28176 28177 28178 28179 28180 28181 28182 28183 28184 28185 28186 28187 28188 28189 28190 28191 28192 28193 28194 28195 28196 28197 28198 28199 28200 28201 28202 28203 28204 28205 28206 28207 28208 28209 28210 28211 28212 28213 28214 28215 28216 28217 28218 28219 28220 28221 28222 28223 28224 28225 28226 28227 28228 28229 28230 28231 28232 28233 28234 28235 28236 28237 28238 28239 28240 28241 28242 28243 28244 28245 28246 28247 28248 28249 28250 28251 28252 28253 28254 28255 28256 28257 28258 28259 28260 28261 28262 28263 28264 28265 28266 28267 28268 28269 28270 28271 28272 28273 28274 28275 28276 28277 28278 28279 28280 28281 28282 28283 28284 28285 28286 28287 28288 28289 28290 28291 28292 28293 28294 28295 28296 28297 28298 28299 28300 28301 28302 28303 28304 28305 28306 28307 28308 28309 28310 28311 28312 28313 28314 28315 28316 28317 28318 28319 28320 28321 28322 28323 28324 28325 28326 28327 28328 28329 28330 28331 28332 28333 28334 28335 28336 28337 28338 28339 28340 28341 28342 28343 28344 28345 28346 28347 28348 28349 28350 28351 28352 28353 28354 28355 28356 28357 28358 28359 28360 28361 28362 28363 28364 28365 28366 28367 28368 28369 28370 28371 28372 28373 28374 28375 28376 28377 28378 28379 28380 28381 28382 28383 28384 28385 28386 28387 28388 28389 28390 28391 28392 28393 28394 28395 28396 28397 28398 28399 28400 28401 28402 28403 28404 28405 28406 28407 28408 28409 28410 28411 28412 28413 28414 28415 28416 28417 28418 28419 28420 28421 28422 28423 28424 28425 28426 28427 28428 28429 28430 28431 28432 28433 28434 28435 28436 28437 28438 28439 28440 28441 28442 28443 28444 28445 28446 28447 28448 28449 28450 28451 28452 28453 28454 28455 28456 28457 28458 28459 28460 28461 28462 28463 28464 28465 28466 28467 28468 28469 28470 28471 28472 28473 28474 28475 28476 28477 28478 28479 28480 28481 28482 28483 28484 28485 28486 28487 28488 28489 28490 28491 28492 28493 28494 28495 28496 28497 28498 28499 28500 28501 28502 28503 28504 28505 28506 28507 28508 28509 28510 28511 28512 28513 28514 28515 28516 28517 28518 28519 28520 28521 28522 28523 28524 28525 28526 28527 28528 28529 28530 28531 28532 28533 28534 28535 28536 28537 28538 28539 28540 28541 28542 28543 28544 28545 28546 28547 28548 28549 28550 28551 28552 28553 28554 28555 28556 28557 28558 28559 28560 28561 28562 28563 28564 28565 28566 28567 28568 28569 28570 28571 28572 28573 28574 28575 28576 28577 28578 28579 28580 28581 28582 28583 28584 28585 28586 28587 28588 28589 28590 28591 28592 28593 28594 28595 28596 28597 28598 28599 28600 28601 28602 28603 28604 28605 28606 28607 28608 28609 28610 28611 28612 28613 28614 28615 28616 28617 28618 28619 28620 28621 28622 28623 28624 28625 28626 28627 28628 28629 28630 28631 28632 28633 28634 28635 28636 28637 28638 28639 28640 28641 28642 28643 28644 28645 28646 28647 28648 28649 28650 28651 28652 28653 28654 28655 28656 28657 28658 28659 28660 28661 28662 28663 28664 28665 28666 28667 28668 28669 28670 28671 28672 28673 28674 28675 28676 28677 28678 28679 28680 28681 28682 28683 28684 28685 28686 28687 28688 28689 28690 28691 28692 28693 28694 28695 28696 28697 28698 28699 28700 28701 28702 28703 28704 28705 28706 28707 28708 28709 28710 28711 28712 28713 28714 28715 28716 28717 28718 28719 28720 28721 28722 28723 28724 28725 28726 28727 28728 28729 28730 28731 28732 28733 28734 28735 28736 28737 28738 28739 28740 28741 28742 28743 28744 28745 28746 28747 28748 28749 28750 28751 28752 28753 28754 28755 28756 28757 28758 28759 28760 28761 28762 28763 28764 28765 28766 28767 28768 28769 28770 28771 28772 28773 28774 28775 28776 28777 28778 28779 28780 28781 28782 28783 28784 28785 28786 28787 28788 28789 28790 28791 28792 28793 28794 28795 28796 28797 28798 28799 28800 28801 28802 28803 28804 28805 28806 28807 28808 28809 28810 28811 28812 28813 28814 28815 28816 28817 28818 28819 28820 28821 28822 28823 28824 28825 28826 28827 28828 28829 28830 28831 28832 28833 28834 28835 28836 28837 28838 28839 28840 28841 28842 28843 28844 28845 28846 28847 28848 28849 28850 28851 28852 28853 28854 28855 28856 28857 28858 28859 28860 28861 28862 28863 28864 28865 28866 28867 28868 28869 28870 28871 28872 28873 28874 28875 28876 28877 28878 28879 28880 28881 28882 28883 28884 28885 28886 28887 28888 28889 28890 28891 28892 28893 28894 28895 28896 28897 28898 28899 28900 28901 28902 28903 28904 28905 28906 28907 28908 28909 28910 28911 28912 28913 28914 28915 28916 28917 28918 28919 28920 28921 28922 28923 28924 28925 28926 28927 28928 28929 28930 28931 28932 28933 28934 28935 28936 28937 28938 28939 28940 28941 28942 28943 28944 28945 28946 28947 28948 28949 28950 28951 28952 28953 28954 28955 28956 28957 28958 28959 28960 28961 28962 28963 28964 28965 28966 28967 28968 28969 28970 28971 28972 28973 28974 28975 28976 28977 28978 28979 28980 28981 28982 28983 28984 28985 28986 28987 28988 28989 28990 28991 28992 28993 28994 28995 28996 28997 28998 28999 29000 29001 29002 29003 29004 29005 29006 29007 29008 29009 29010 29011 29012 29013 29014 29015 29016 29017 29018 29019 29020 29021 29022 29023 29024 29025 29026 29027 29028 29029 29030 29031 29032 29033 29034 29035 29036 29037 29038 29039 29040 29041 29042 29043 29044 29045 29046 29047 29048 29049 29050 29051 29052 29053 29054 29055 29056 29057 29058 29059 29060 29061 29062 29063 29064 29065 29066 29067 29068 29069 29070 29071 29072 29073 29074 29075 29076 29077 29078 29079 29080 29081 29082 29083 29084 29085 29086 29087 29088 29089 29090 29091 29092 29093 29094 29095 29096 29097 29098 29099 29100 29101 29102 29103 29104 29105 29106 29107 29108 29109 29110 29111 29112 29113 29114 29115 29116 29117 29118 29119 29120 29121 29122 29123 29124 29125 29126 29127 29128 29129 29130 29131 29132 29133 29134 29135 29136 29137 29138 29139 29140 29141 29142 29143 29144 29145 29146 29147 29148 29149 29150 29151 29152 29153 29154 29155 29156 29157 29158 29159 29160 29161 29162 29163 29164 29165 29166 29167 29168 29169 29170 29171 29172 29173 29174 29175 29176 29177 29178 29179 29180 29181 29182 29183 29184 29185 29186 29187 29188 29189 29190 29191 29192 29193 29194 29195 29196 29197 29198 29199 29200 29201 29202 29203 29204 29205 29206 29207 29208 29209 29210 29211 29212 29213 29214 29215 29216 29217 29218 29219 29220 29221 29222 29223 29224 29225 29226 29227 29228 29229 29230 29231 29232 29233 29234 29235 29236 29237 29238 29239 29240 29241 29242 29243 29244 29245 29246 29247 29248 29249 29250 29251 29252 29253 29254 29255 29256 29257 29258 29259 29260 29261 29262 29263 29264 29265 29266 29267 29268 29269 29270 29271 29272 29273 29274 29275 29276 29277 29278 29279 29280 29281 29282 29283 29284 29285 29286 29287 29288 29289 29290 29291 29292 29293 29294 29295 29296 29297 29298 29299 29300 29301 29302 29303 29304 29305 29306 29307 29308 29309 29310 29311 29312 29313 29314 29315 29316 29317 29318 29319 29320 29321 29322 29323 29324 29325 29326 29327 29328 29329 29330 29331 29332 29333 29334 29335 29336 29337 29338 29339 29340 29341 29342 29343 29344 29345 29346 29347 29348 29349 29350 29351 29352 29353 29354 29355 29356 29357 29358 29359 29360 29361 29362 29363 29364 29365 29366 29367 29368 29369 29370 29371 29372 29373 29374 29375 29376 29377 29378 29379 29380 29381 29382 29383 29384 29385 29386 29387 29388 29389 29390 29391 29392 29393 29394 29395 29396 29397 29398 29399 29400 29401 29402 29403 29404 29405 29406 29407 29408 29409 29410 29411 29412 29413 29414 29415 29416 29417 29418 29419 29420 29421 29422 29423 29424 29425 29426 29427 29428 29429 29430 29431 29432 29433 29434 29435 29436 29437 29438 29439 29440 29441 29442 29443 29444 29445 29446 29447 29448 29449 29450 29451 29452 29453 29454 29455 29456 29457 29458 29459 29460 29461 29462 29463 29464 29465 29466 29467 29468 29469 29470 29471 29472 29473 29474 29475 29476 29477 29478 29479 29480 29481 29482 29483 29484 29485 29486 29487 29488 29489 29490 29491 29492 29493 29494 29495 29496 29497 29498 29499 29500 29501 29502 29503 29504 29505 29506 29507 29508 29509 29510 29511 29512 29513 29514 29515 29516 29517 29518 29519 29520 29521 29522 29523 29524 29525 29526 29527 29528 29529 29530 29531 29532 29533 29534 29535 29536 29537 29538 29539 29540 29541 29542 29543 29544 29545 29546 29547 29548 29549 29550 29551 29552 29553 29554 29555 29556 29557 29558 29559 29560 29561 29562 29563 29564 29565 29566 29567 29568 29569 29570 29571 29572 29573 29574 29575 29576 29577 29578 29579 29580 29581 29582 29583 29584 29585 29586 29587 29588 29589 29590 29591 29592 29593 29594 29595 29596 29597 29598 29599 29600 29601 29602 29603 29604 29605 29606 29607 29608 29609 29610 29611 29612 29613 29614 29615 29616 29617 29618 29619 29620 29621 29622 29623 29624 29625 29626 29627 29628 29629 29630 29631 29632 29633 29634 29635 29636 29637 29638 29639 29640 29641 29642 29643 29644 29645 29646 29647 29648 29649 29650 29651 29652 29653 29654 29655 29656 29657 29658 29659 29660 29661 29662 29663 29664 29665 29666 29667 29668 29669 29670 29671 29672 29673 29674 29675 29676 29677 29678 29679 29680 29681 29682 29683 29684 29685 29686 29687 29688 29689 29690 29691 29692 29693 29694 29695 29696 29697 29698 29699 29700 29701 29702 29703 29704 29705 29706 29707 29708 29709 29710 29711 29712 29713 29714 29715 29716 29717 29718 29719 29720 29721 29722 29723 29724 29725 29726 29727 29728 29729 29730 29731 29732 29733 29734 29735 29736 29737 29738 29739 29740 29741 29742 29743 29744 29745 29746 29747 29748 29749 29750 29751 29752 29753 29754 29755 29756 29757 29758 29759 29760 29761 29762 29763 29764 29765 29766 29767 29768 29769 29770 29771 29772 29773 29774 29775 29776 29777 29778 29779 29780 29781 29782 29783 29784 29785 29786 29787 29788 29789 29790 29791 29792 29793 29794 29795 29796 29797 29798 29799 29800 29801 29802 29803 29804 29805 29806 29807 29808 29809 29810 29811 29812 29813 29814 29815 29816 29817 29818 29819 29820 29821 29822 29823 29824 29825 29826 29827 29828 29829 29830 29831 29832 29833 29834 29835 29836 29837 29838 29839 29840 29841 29842 29843 29844 29845 29846 29847 29848 29849 29850 29851 29852 29853 29854 29855 29856 29857 29858 29859 29860 29861 29862 29863 29864 29865 29866 29867 29868 29869 29870 29871 29872 29873 29874 29875 29876 29877 29878 29879 29880 29881 29882 29883 29884 29885 29886 29887 29888 29889 29890 29891 29892 29893 29894 29895 29896 29897 29898 29899 29900 29901 29902 29903 29904 29905 29906 29907 29908 29909 29910 29911 29912 29913 29914 29915 29916 29917 29918 29919 29920 29921 29922 29923 29924 29925 29926 29927 29928 29929 29930 29931 29932 29933 29934 29935 29936 29937 29938 29939 29940 29941 29942 29943 29944 29945 29946 29947 29948 29949 29950 29951 29952 29953 29954 29955 29956 29957 29958 29959 29960 29961 29962 29963 29964 29965 29966 29967 29968 29969 29970 29971 29972 29973 29974 29975 29976 29977 29978 29979 29980 29981 29982 29983 29984 29985 29986 29987 29988 29989 29990 29991 29992 29993 29994 29995 29996 29997 29998 29999 30000 30001 30002 30003 30004 30005 30006 30007 30008 30009 30010 30011 30012 30013 30014 30015 30016 30017 30018 30019 30020 30021 30022 30023 30024 30025 30026 30027 30028 30029 30030 30031 30032 30033 30034 30035 30036 30037 30038 30039 30040 30041 30042 30043 30044 30045 30046 30047 30048 30049 30050 30051 30052 30053 30054 30055 30056 30057 30058 30059 30060 30061 30062 30063 30064 30065 30066 30067 30068 30069 30070 30071 30072 30073 30074 30075 30076 30077 30078 30079 30080 30081 30082 30083 30084 30085 30086 30087 30088 30089 30090 30091 30092 30093 30094 30095 30096 30097 30098 30099 30100 30101 30102 30103 30104 30105 30106 30107 30108 30109 30110 30111 30112 30113 30114 30115 30116 30117 30118 30119 30120 30121 30122 30123 30124 30125 30126 30127 30128 30129 30130 30131 30132 30133 30134 30135 30136 30137 30138 30139 30140 30141 30142 30143 30144 30145 30146 30147 30148 30149 30150 30151 30152 30153 30154 30155 30156 30157 30158 30159 30160 30161 30162 30163 30164 30165 30166 30167 30168 30169 30170 30171 30172 30173 30174 30175 30176 30177 30178 30179 30180 30181 30182 30183 30184 30185 30186 30187 30188 30189 30190 30191 30192 30193 30194 30195 30196 30197 30198 30199 30200 30201 30202 30203 30204 30205 30206 30207 30208 30209 30210 30211 30212 30213 30214 30215 30216 30217 30218 30219 30220 30221 30222 30223 30224 30225 30226 30227 30228 30229 30230 30231 30232 30233 30234 30235 30236 30237 30238 30239 30240 30241 30242 30243 30244 30245 30246 30247 30248 30249 30250 30251 30252 30253 30254 30255 30256 30257 30258 30259 30260 30261 30262 30263 30264 30265 30266 30267 30268 30269 30270 30271 30272 30273 30274 30275 30276 30277 30278 30279 30280 30281 30282 30283 30284 30285 30286 30287 30288 30289 30290 30291 30292 30293 30294 30295 30296 30297 30298 30299 30300 30301 30302 30303 30304 30305 30306 30307 30308 30309 30310 30311 30312 30313 30314 30315 30316 30317 30318 30319 30320 30321 30322 30323 30324 30325 30326 30327 30328 30329 30330 30331 30332 30333 30334 30335 30336 30337 30338 30339 30340 30341 30342 30343 30344 30345 30346 30347 30348 30349 30350 30351 30352 30353 30354 30355 30356 30357 30358 30359 30360 30361 30362 30363 30364 30365 30366 30367 30368 30369 30370 30371 30372 30373 30374 30375 30376 30377 30378 30379 30380 30381 30382 30383 30384 30385 30386 30387 30388 30389 30390 30391 30392 30393 30394 30395 30396 30397 30398 30399 30400 30401 30402 30403 30404 30405 30406 30407 30408 30409 30410 30411 30412 30413 30414 30415 30416 30417 30418 30419 30420 30421 30422 30423 30424 30425 30426 30427 30428 30429 30430 30431 30432 30433 30434 30435 30436 30437 30438 30439 30440 30441 30442 30443 30444 30445 30446 30447 30448 30449 30450 30451 30452 30453 30454 30455 30456 30457 30458 30459 30460 30461 30462 30463 30464 30465 30466 30467 30468 30469 30470 30471 30472 30473 30474 30475 30476 30477 30478 30479 30480 30481 30482 30483 30484 30485 30486 30487 30488 30489 30490 30491 30492 30493 30494 30495 30496 30497 30498 30499 30500 30501 30502 30503 30504 30505 30506 30507 30508 30509 30510 30511 30512 30513 30514 30515 30516 30517 30518 30519 30520 30521 30522 30523 30524 30525 30526 30527 30528 30529 30530 30531 30532 30533 30534 30535 30536 30537 30538 30539 30540 30541 30542 30543 30544 30545 30546 30547 30548 30549 30550 30551 30552 30553 30554 30555 30556 30557 30558 30559 30560 30561 30562 30563 30564 30565 30566 30567 30568 30569 30570 30571 30572 30573 30574 30575 30576 30577 30578 30579 30580 30581 30582 30583 30584 30585 30586 30587 30588 30589 30590 30591 30592 30593 30594 30595 30596 30597 30598 30599 30600 30601 30602 30603 30604 30605 30606 30607 30608 30609 30610 30611 30612 30613 30614 30615 30616 30617 30618 30619 30620 30621 30622 30623 30624 30625 30626 30627 30628 30629 30630 30631 30632 30633 30634 30635 30636 30637 30638 30639 30640 30641 30642 30643 30644 30645 30646 30647 30648 30649 30650 30651 30652 30653 30654 30655 30656 30657 30658 30659 30660 30661 30662 30663 30664 30665 30666 30667 30668 30669 30670 30671 30672 30673 30674 30675 30676 30677 30678 30679 30680 30681 30682 30683 30684 30685 30686 30687 30688 30689 30690 30691 30692 30693 30694 30695 30696 30697 30698 30699 30700 30701 30702 30703 30704 30705 30706 30707 30708 30709 30710 30711 30712 30713 30714 30715 30716 30717 30718 30719 30720 30721 30722 30723 30724 30725 30726 30727 30728 30729 30730 30731 30732 30733 30734 30735 30736 30737 30738 30739 30740 30741 30742 30743 30744 30745 30746 30747 30748 30749 30750 30751 30752 30753 30754 30755 30756 30757 30758 30759 30760 30761 30762 30763 30764 30765 30766 30767 30768 30769 30770 30771 30772 30773 30774 30775 30776 30777 30778 30779 30780 30781 30782 30783 30784 30785 30786 30787 30788 30789 30790 30791 30792 30793 30794 30795 30796 30797 30798 30799 30800 30801 30802 30803 30804 30805 30806 30807 30808 30809 30810 30811 30812 30813 30814 30815 30816 30817 30818 30819 30820 30821 30822 30823 30824 30825 30826 30827 30828 30829 30830 30831 30832 30833 30834 30835 30836 30837 30838 30839 30840 30841 30842 30843 30844 30845 30846 30847 30848 30849 30850 30851 30852 30853 30854 30855 30856 30857 30858 30859 30860 30861 30862 30863 30864 30865 30866 30867 30868 30869 30870 30871 30872 30873 30874 30875 30876 30877 30878 30879 30880 30881 30882 30883 30884 30885 30886 30887 30888 30889 30890 30891 30892 30893 30894 30895 30896 30897 30898 30899 30900 30901 30902 30903 30904 30905 30906 30907 30908 30909 30910 30911 30912 30913 30914 30915 30916 30917 30918 30919 30920 30921 30922 30923 30924 30925 30926 30927 30928 30929 30930 30931 30932 30933 30934 30935 30936 30937 30938 30939 30940 30941 30942 30943 30944 30945 30946 30947 30948 30949 30950 30951 30952 30953 30954 30955 30956 30957 30958 30959 30960 30961 30962 30963 30964 30965 30966 30967 30968 30969 30970 30971 30972 30973 30974 30975 30976 30977 30978 30979 30980 30981 30982 30983 30984 30985 30986 30987 30988 30989 30990 30991 30992 30993 30994 30995 30996 30997 30998 30999 31000 31001 31002 31003 31004 31005 31006 31007 31008 31009 31010 31011 31012 31013 31014 31015 31016 31017 31018 31019 31020 31021 31022 31023 31024 31025 31026 31027 31028 31029 31030 31031 31032 31033 31034 31035 31036 31037 31038 31039 31040 31041 31042 31043 31044 31045 31046 31047 31048 31049 31050 31051 31052 31053 31054 31055 31056 31057 31058 31059 31060 31061 31062 31063 31064 31065 31066 31067 31068 31069 31070 31071 31072 31073 31074 31075 31076 31077 31078 31079 31080 31081 31082 31083 31084 31085 31086 31087 31088 31089 31090 31091 31092 31093 31094 31095 31096 31097 31098 31099 31100 31101 31102 31103 31104 31105 31106 31107 31108 31109 31110 31111 31112 31113 31114 31115 31116 31117 31118 31119 31120 31121 31122 31123 31124 31125 31126 31127 31128 31129 31130 31131 31132 31133 31134 31135 31136 31137 31138 31139 31140 31141 31142 31143 31144 31145 31146 31147 31148 31149 31150 31151 31152 31153 31154 31155 31156 31157 31158 31159 31160 31161 31162 31163 31164 31165 31166 31167 31168 31169 31170 31171 31172 31173 31174 31175 31176 31177 31178 31179 31180 31181 31182 31183 31184 31185 31186 31187 31188 31189 31190 31191 31192 31193 31194 31195 31196 31197 31198 31199 31200 31201 31202 31203 31204 31205 31206 31207 31208 31209 31210 31211 31212 31213 31214 31215 31216 31217 31218 31219 31220 31221 31222 31223 31224 31225 31226 31227 31228 31229 31230 31231 31232 31233 31234 31235 31236 31237 31238 31239 31240 31241 31242 31243 31244 31245 31246 31247 31248 31249 31250 31251 31252 31253 31254 31255 31256 31257 31258 31259 31260 31261 31262 31263 31264 31265 31266 31267 31268 31269 31270 31271 31272 31273 31274 31275 31276 31277 31278 31279 31280 31281 31282 31283 31284 31285 31286 31287 31288 31289 31290 31291 31292 31293 31294 31295 31296 31297 31298 31299 31300 31301 31302 31303 31304 31305 31306 31307 31308 31309 31310 31311 31312 31313 31314 31315 31316 31317 31318 31319 31320 31321 31322 31323 31324 31325 31326 31327 31328 31329 31330 31331 31332 31333 31334 31335 31336 31337 31338 31339 31340 31341 31342 31343 31344 31345 31346 31347 31348 31349 31350 31351 31352 31353 31354 31355 31356 31357 31358 31359 31360 31361 31362 31363 31364 31365 31366 31367 31368 31369 31370 31371 31372 31373 31374 31375 31376 31377 31378 31379 31380 31381 31382 31383 31384 31385 31386 31387 31388 31389 31390 31391 31392 31393 31394 31395 31396 31397 31398 31399 31400 31401 31402 31403 31404 31405 31406 31407 31408 31409 31410 31411 31412 31413 31414 31415 31416 31417 31418 31419 31420 31421 31422 31423 31424 31425 31426 31427 31428 31429 31430 31431 31432 31433 31434 31435 31436 31437 31438 31439 31440 31441 31442 31443 31444 31445 31446 31447 31448 31449 31450 31451 31452 31453 31454 31455 31456 31457 31458 31459 31460 31461 31462 31463 31464 31465 31466 31467 31468 31469 31470 31471 31472 31473 31474 31475 31476 31477 31478 31479 31480 31481 31482 31483 31484 31485 31486 31487 31488 31489 31490 31491 31492 31493 31494 31495 31496 31497 31498 31499 31500 31501 31502 31503 31504 31505 31506 31507 31508 31509 31510 31511 31512 31513 31514 31515 31516 31517 31518 31519 31520 31521 31522 31523 31524 31525 31526 31527 31528 31529 31530 31531 31532 31533 31534 31535 31536 31537 31538 31539 31540 31541 31542 31543 31544 31545 31546 31547 31548 31549 31550 31551 31552 31553 31554 31555 31556 31557 31558 31559 31560 31561 31562 31563 31564 31565 31566 31567 31568 31569 31570 31571 31572 31573 31574 31575 31576 31577 31578 31579 31580 31581 31582 31583 31584 31585 31586 31587 31588 31589 31590 31591 31592 31593 31594 31595 31596 31597 31598 31599 31600 31601 31602 31603 31604 31605 31606 31607 31608 31609 31610 31611 31612 31613 31614 31615 31616 31617 31618 31619 31620 31621 31622 31623 31624 31625 31626 31627 31628 31629 31630 31631 31632 31633 31634 31635 31636 31637 31638 31639 31640 31641 31642 31643 31644 31645 31646 31647 31648 31649 31650 31651 31652 31653 31654 31655 31656 31657 31658 31659 31660 31661 31662 31663 31664 31665 31666 31667 31668 31669 31670 31671 31672 31673 31674 31675 31676 31677 31678 31679 31680 31681 31682 31683 31684 31685 31686 31687 31688 31689 31690 31691 31692 31693 31694 31695 31696 31697 31698 31699 31700 31701 31702 31703 31704 31705 31706 31707 31708 31709 31710 31711 31712 31713 31714 31715 31716 31717 31718 31719 31720 31721 31722 31723 31724 31725 31726 31727 31728 31729 31730 31731 31732 31733 31734 31735 31736 31737 31738 31739 31740 31741 31742 31743 31744 31745 31746 31747 31748 31749 31750 31751 31752 31753 31754 31755 31756 31757 31758 31759 31760 31761 31762 31763 31764 31765 31766 31767 31768 31769 31770 31771 31772 31773 31774 31775 31776 31777 31778 31779 31780 31781 31782 31783 31784 31785 31786 31787 31788 31789 31790 31791 31792 31793 31794 31795 31796 31797 31798 31799 31800 31801 31802 31803 31804 31805 31806 31807 31808 31809 31810 31811 31812 31813 31814 31815 31816 31817 31818 31819 31820 31821 31822 31823 31824 31825 31826 31827 31828 31829 31830 31831 31832 31833 31834 31835 31836 31837 31838 31839 31840 31841 31842 31843 31844 31845 31846 31847 31848 31849 31850 31851 31852 31853 31854 31855 31856 31857 31858 31859 31860 31861 31862 31863 31864 31865 31866 31867 31868 31869 31870 31871 31872 31873 31874 31875 31876 31877 31878 31879 31880 31881 31882 31883 31884 31885 31886 31887 31888 31889 31890 31891 31892 31893 31894 31895 31896 31897 31898 31899 31900 31901 31902 31903 31904 31905 31906 31907 31908 31909 31910 31911 31912 31913 31914 31915 31916 31917 31918 31919 31920 31921 31922 31923 31924 31925 31926 31927 31928 31929 31930 31931 31932 31933 31934 31935 31936 31937 31938 31939 31940 31941 31942 31943 31944 31945 31946 31947 31948 31949 31950 31951 31952 31953 31954 31955 31956 31957 31958 31959 31960 31961 31962 31963 31964 31965 31966 31967 31968 31969 31970 31971 31972 31973 31974 31975 31976 31977 31978 31979 31980 31981 31982 31983 31984 31985 31986 31987 31988 31989 31990 31991 31992 31993 31994 31995 31996 31997 31998 31999 32000 32001 32002 32003 32004 32005 32006 32007 32008 32009 32010 32011 32012 32013 32014 32015 32016 32017 32018 32019 32020 32021 32022 32023 32024 32025 32026 32027 32028 32029 32030 32031 32032 32033 32034 32035 32036 32037 32038 32039 32040 32041 32042 32043 32044 32045 32046 32047 32048 32049 32050 32051 32052 32053 32054 32055 32056 32057 32058 32059 32060 32061 32062 32063 32064 32065 32066 32067 32068 32069 32070 32071 32072 32073 32074 32075 32076 32077 32078 32079 32080 32081 32082 32083 32084 32085 32086 32087 32088 32089 32090 32091 32092 32093 32094 32095 32096 32097 32098 32099 32100 32101 32102 32103 32104 32105 32106 32107 32108 32109 32110 32111 32112 32113 32114 32115 32116 32117 32118 32119 32120 32121 32122 32123 32124 32125 32126 32127 32128 32129 32130 32131 32132 32133 32134 32135 32136 32137 32138 32139 32140 32141 32142 32143 32144 32145 32146 32147 32148 32149 32150 32151 32152 32153 32154 32155 32156 32157 32158 32159 32160 32161 32162 32163 32164 32165 32166 32167 32168 32169 32170 32171 32172 32173 32174 32175 32176 32177 32178 32179 32180 32181 32182 32183 32184 32185 32186 32187 32188 32189 32190 32191 32192 32193 32194 32195 32196 32197 32198 32199 32200 32201 32202 32203 32204 32205 32206 32207 32208 32209 32210 32211 32212 32213 32214 32215 32216 32217 32218 32219 32220 32221 32222 32223 32224 32225 32226 32227 32228 32229 32230 32231 32232 32233 32234 32235 32236 32237 32238 32239 32240 32241 32242 32243 32244 32245 32246 32247 32248 32249 32250 32251 32252 32253 32254 32255 32256 32257 32258 32259 32260 32261 32262 32263 32264 32265 32266 32267 32268 32269 32270 32271 32272 32273 32274 32275 32276 32277 32278 32279 32280 32281 32282 32283 32284 32285 32286 32287 32288 32289 32290 32291 32292 32293 32294 32295 32296 32297 32298 32299 32300 32301 32302 32303 32304 32305 32306 32307 32308 32309 32310 32311 32312 32313 32314 32315 32316 32317 32318 32319 32320 32321 32322 32323 32324 32325 32326 32327 32328 32329 32330 32331 32332 32333 32334 32335 32336 32337 32338 32339 32340 32341 32342 32343 32344 32345 32346 32347 32348 32349 32350 32351 32352 32353 32354 32355 32356 32357 32358 32359 32360 32361 32362 32363 32364 32365 32366 32367 32368 32369 32370 32371 32372 32373 32374 32375 32376 32377 32378 32379 32380 32381 32382 32383 32384 32385 32386 32387 32388 32389 32390 32391 32392 32393 32394 32395 32396 32397 32398 32399 32400 32401 32402 32403 32404 32405 32406 32407 32408 32409 32410 32411 32412 32413 32414 32415 32416 32417 32418 32419 32420 32421 32422 32423 32424 32425 32426 32427 32428 32429 32430 32431 32432 32433 32434 32435 32436 32437 32438 32439 32440 32441 32442 32443 32444 32445 32446 32447 32448 32449 32450 32451 32452 32453 32454 32455 32456 32457 32458 32459 32460 32461 32462 32463 32464 32465 32466 32467 32468 32469 32470 32471 32472 32473 32474 32475 32476 32477 32478 32479 32480 32481 32482 32483 32484 32485 32486 32487 32488 32489 32490 32491 32492 32493 32494 32495 32496 32497 32498 32499 32500 32501 32502 32503 32504 32505 32506 32507 32508 32509 32510 32511 32512 32513 32514 32515 32516 32517 32518 32519 32520 32521 32522 32523 32524 32525 32526 32527 32528 32529 32530 32531 32532 32533 32534 32535 32536 32537 32538 32539 32540 32541 32542 32543 32544 32545 32546 32547 32548 32549 32550 32551 32552 32553 32554 32555 32556 32557 32558 32559 32560 32561 32562 32563 32564 32565 32566 32567 32568 32569 32570 32571 32572 32573 32574 32575 32576 32577 32578 32579 32580 32581 32582 32583 32584 32585 32586 32587 32588 32589 32590 32591 32592 32593 32594 32595 32596 32597 32598 32599 32600 32601 32602 32603 32604 32605 32606 32607 32608 32609 32610 32611 32612 32613 32614 32615 32616 32617 32618 32619 32620 32621 32622 32623 32624 32625 32626 32627 32628 32629 32630 32631 32632 32633 32634 32635 32636 32637 32638 32639 32640 32641 32642 32643 32644 32645 32646 32647 32648 32649 32650 32651 32652 32653 32654 32655 32656 32657 32658 32659 32660 32661 32662 32663 32664 32665 32666 32667 32668 32669 32670 32671 32672 32673 32674 32675 32676 32677 32678 32679 32680 32681 32682 32683 32684 32685 32686 32687 32688 32689 32690 32691 32692 32693 32694 32695 32696 32697 32698 32699 32700 32701 32702 32703 32704 32705 32706 32707 32708 32709 32710 32711 32712 32713 32714 32715 32716 32717 32718 32719 32720 32721 32722 32723 32724 32725 32726 32727 32728 32729 32730 32731 32732 32733 32734 32735 32736 32737 32738 32739 32740 32741 32742 32743 32744 32745 32746 32747 32748 32749 32750 32751 32752 32753 32754 32755 32756 32757 32758 32759 32760 32761 32762 32763 32764 32765 32766 32767 32768 32769 32770 32771 32772 32773 32774 32775 32776 32777 32778 32779 32780 32781 32782 32783 32784 32785 32786 32787 32788 32789 32790 32791 32792 32793 32794 32795 32796 32797 32798 32799 32800 32801 32802 32803 32804 32805 32806 32807 32808 32809 32810 32811 32812 32813 32814 32815 32816 32817 32818 32819 32820 32821 32822 32823 32824 32825 32826 32827 32828 32829 32830 32831 32832 32833 32834 32835 32836 32837 32838 32839 32840 32841 32842 32843 32844 32845 32846 32847 32848 32849 32850 32851 32852 32853 32854 32855 32856 32857 32858 32859 32860 32861 32862 32863 32864 32865 32866 32867 32868 32869 32870 32871 32872 32873 32874 32875 32876 32877 32878 32879 32880 32881 32882 32883 32884 32885 32886 32887 32888 32889 32890 32891 32892 32893 32894 32895 32896 32897 32898 32899 32900 32901 32902 32903 32904 32905 32906 32907 32908 32909 32910 32911 32912 32913 32914 32915 32916 32917 32918 32919 32920 32921 32922 32923 32924 32925 32926 32927 32928 32929 32930 32931 32932 32933 32934 32935 32936 32937 32938 32939 32940 32941 32942 32943 32944 32945 32946 32947 32948 32949 32950 32951 32952 32953 32954 32955 32956 32957 32958 32959 32960 32961 32962 32963 32964 32965 32966 32967 32968 32969 32970 32971 32972 32973 32974 32975 32976 32977 32978 32979 32980 32981 32982 32983 32984 32985 32986 32987 32988 32989 32990 32991 32992 32993 32994 32995 32996 32997 32998 32999 33000 33001 33002 33003 33004 33005 33006 33007 33008 33009 33010 33011 33012 33013 33014 33015 33016 33017 33018 33019 33020 33021 33022 33023 33024 33025 33026 33027 33028 33029 33030 33031 33032 33033 33034 33035 33036 33037 33038 33039 33040 33041 33042 33043 33044 33045 33046 33047 33048 33049 33050 33051 33052 33053 33054 33055 33056 33057 33058 33059 33060 33061 33062 33063 33064 33065 33066 33067 33068 33069 33070 33071 33072 33073 33074 33075 33076 33077 33078 33079 33080 33081 33082 33083 33084 33085 33086 33087 33088 33089 33090 33091 33092 33093 33094 33095 33096 33097 33098 33099 33100 33101 33102 33103 33104 33105 33106 33107 33108 33109 33110 33111 33112 33113 33114 33115 33116 33117 33118 33119 33120 33121 33122 33123 33124 33125 33126 33127 33128 33129 33130 33131 33132 33133 33134 33135 33136 33137 33138 33139 33140 33141 33142 33143 33144 33145 33146 33147 33148 33149 33150 33151 33152 33153 33154 33155 33156 33157 33158 33159 33160 33161 33162 33163 33164 33165 33166 33167 33168 33169 33170 33171 33172 33173 33174 33175 33176 33177 33178 33179 33180 33181 33182 33183 33184 33185 33186 33187 33188 33189 33190 33191 33192 33193 33194 33195 33196 33197 33198 33199 33200 33201 33202 33203 33204 33205 33206 33207 33208 33209 33210 33211 33212 33213 33214 33215 33216 33217 33218 33219 33220 33221 33222 33223 33224 33225 33226 33227 33228 33229 33230 33231 33232 33233 33234 33235 33236 33237 33238 33239 33240 33241 33242 33243 33244 33245 33246 33247 33248 33249 33250 33251 33252 33253 33254 33255 33256 33257 33258 33259 33260 33261 33262 33263 33264 33265 33266 33267 33268 33269 33270 33271 33272 33273 33274 33275 33276 33277 33278 33279 33280 33281 33282 33283 33284 33285 33286 33287 33288 33289 33290 33291 33292 33293 33294 33295 33296 33297 33298 33299 33300 33301 33302 33303 33304 33305 33306 33307 33308 33309 33310 33311 33312 33313 33314 33315 33316 33317 33318 33319 33320 33321 33322 33323 33324 33325 33326 33327 33328 33329 33330 33331 33332 33333 33334 33335 33336 33337 33338 33339 33340 33341 33342 33343 33344 33345 33346 33347 33348 33349 33350 33351 33352 33353 33354 33355 33356 33357 33358 33359 33360 33361 33362 33363 33364 33365 33366 33367 33368 33369 33370 33371 33372 33373 33374 33375 33376 33377 33378 33379 33380 33381 33382 33383 33384 33385 33386 33387 33388 33389 33390 33391 33392 33393 33394 33395 33396 33397 33398 33399 33400 33401 33402 33403 33404 33405 33406 33407 33408 33409 33410 33411 33412 33413 33414 33415 33416 33417 33418 33419 33420 33421 33422 33423 33424 33425 33426 33427 33428 33429 33430 33431 33432 33433 33434 33435 33436 33437 33438 33439 33440 33441 33442 33443 33444 33445 33446 33447 33448 33449 33450 33451 33452 33453 33454 33455 33456 33457 33458 33459 33460 33461 33462 33463 33464 33465 33466 33467 33468 33469 33470 33471 33472 33473 33474 33475 33476 33477 33478 33479 33480 33481 33482 33483 33484 33485 33486 33487 33488 33489 33490 33491 33492 33493 33494 33495 33496 33497 33498 33499 33500 33501 33502 33503 33504 33505 33506 33507 33508 33509 33510 33511 33512 33513 33514 33515 33516 33517 33518 33519 33520 33521 33522 33523 33524 33525 33526 33527 33528 33529 33530 33531 33532 33533 33534 33535 33536 33537 33538 33539 33540 33541 33542 33543 33544 33545 33546 33547 33548 33549 33550 33551 33552 33553 33554 33555 33556 33557 33558 33559 33560 33561 33562 33563 33564 33565 33566 33567 33568 33569 33570 33571 33572 33573 33574 33575 33576 33577 33578 33579 33580 33581 33582 33583 33584 33585 33586 33587 33588 33589 33590 33591 33592 33593 33594 33595 33596 33597 33598 33599 33600 33601 33602 33603 33604 33605 33606 33607 33608 33609 33610 33611 33612 33613 33614 33615 33616 33617 33618 33619 33620 33621 33622 33623 33624 33625 33626 33627 33628 33629 33630 33631 33632 33633 33634 33635 33636 33637 33638 33639 33640 33641 33642 33643 33644 33645 33646 33647 33648 33649 33650 33651 33652 33653 33654 33655 33656 33657 33658 33659 33660 33661 33662 33663 33664 33665 33666 33667 33668 33669 33670 33671 33672 33673 33674 33675 33676 33677 33678 33679 33680 33681 33682 33683 33684 33685 33686 33687 33688 33689 33690 33691 33692 33693 33694 33695 33696 33697 33698 33699 33700 33701 33702 33703 33704 33705 33706 33707 33708 33709 33710 33711 33712 33713 33714 33715 33716 33717 33718 33719 33720 33721 33722 33723 33724 33725 33726 33727 33728 33729 33730 33731 33732 33733 33734 33735 33736 33737 33738 33739 33740 33741 33742 33743 33744 33745 33746 33747 33748 33749 33750 33751 33752 33753 33754 33755 33756 33757 33758 33759 33760 33761 33762 33763 33764 33765 33766 33767 33768 33769 33770 33771 33772 33773 33774 33775 33776 33777 33778 33779 33780 33781 33782 33783 33784 33785 33786 33787 33788 33789 33790 33791 33792 33793 33794 33795 33796 33797 33798 33799 33800 33801 33802 33803 33804 33805 33806 33807 33808 33809 33810 33811 33812 33813 33814 33815 33816 33817 33818 33819 33820 33821 33822 33823 33824 33825 33826 33827 33828 33829 33830 33831 33832 33833 33834 33835 33836 33837 33838 33839 33840 33841 33842 33843 33844 33845 33846 33847 33848 33849 33850 33851 33852 33853 33854 33855 33856 33857 33858 33859 33860 33861 33862 33863 33864 33865 33866 33867 33868 33869 33870 33871 33872 33873 33874 33875 33876 33877 33878 33879 33880 33881 33882 33883 33884 33885 33886 33887 33888 33889 33890 33891 33892 33893 33894 33895 33896 33897 33898 33899 33900 33901 33902 33903 33904 33905 33906 33907 33908 33909 33910 33911 33912 33913 33914 33915 33916 33917 33918 33919 33920 33921 33922 33923 33924 33925 33926 33927 33928 33929 33930 33931 33932 33933 33934 33935 33936 33937 33938 33939 33940 33941 33942 33943 33944 33945 33946 33947 33948 33949 33950 33951 33952 33953 33954 33955 33956 33957 33958 33959 33960 33961 33962 33963 33964 33965 33966 33967 33968 33969 33970 33971 33972 33973 33974 33975 33976 33977 33978 33979 33980 33981 33982 33983 33984 33985 33986 33987 33988 33989 33990 33991 33992 33993 33994 33995 33996 33997 33998 33999 34000 34001 34002 34003 34004 34005 34006 34007 34008 34009 34010 34011 34012 34013 34014 34015 34016 34017 34018 34019 34020 34021 34022 34023 34024 34025 34026 34027 34028 34029 34030 34031 34032 34033 34034 34035 34036 34037 34038 34039 34040 34041 34042 34043 34044 34045 34046 34047 34048 34049 34050 34051 34052 34053 34054 34055 34056 34057 34058 34059 34060 34061 34062 34063 34064 34065 34066 34067 34068 34069 34070 34071 34072 34073 34074 34075 34076 34077 34078 34079 34080 34081 34082 34083 34084 34085 34086 34087 34088 34089 34090 34091 34092 34093 34094 34095 34096 34097 34098 34099 34100 34101 34102 34103 34104 34105 34106 34107 34108 34109 34110 34111 34112 34113 34114 34115 34116 34117 34118 34119 34120 34121 34122 34123 34124 34125 34126 34127 34128 34129 34130 34131 34132 34133 34134 34135 34136 34137 34138 34139 34140 34141 34142 34143 34144 34145 34146 34147 34148 34149 34150 34151 34152 34153 34154 34155 34156 34157 34158 34159 34160 34161 34162 34163 34164 34165 34166 34167 34168 34169 34170 34171 34172 34173 34174 34175 34176 34177 34178 34179 34180 34181 34182 34183 34184 34185 34186 34187 34188 34189 34190 34191 34192 34193 34194 34195 34196 34197 34198 34199 34200 34201 34202 34203 34204 34205 34206 34207 34208 34209 34210 34211 34212 34213 34214 34215 34216 34217 34218 34219 34220 34221 34222 34223 34224 34225 34226 34227 34228 34229 34230 34231 34232 34233 34234 34235 34236 34237 34238 34239 34240 34241 34242 34243 34244 34245 34246 34247 34248 34249 34250 34251 34252 34253 34254 34255 34256 34257 34258 34259 34260 34261 34262 34263 34264 34265 34266 34267 34268 34269 34270 34271 34272 34273 34274 34275 34276 34277 34278 34279 34280 34281 34282 34283 34284 34285 34286 34287 34288 34289 34290 34291 34292 34293 34294 34295 34296 34297 34298 34299 34300 34301 34302 34303 34304 34305 34306 34307 34308 34309 34310 34311 34312 34313 34314 34315 34316 34317 34318 34319 34320 34321 34322 34323 34324 34325 34326 34327 34328 34329 34330 34331 34332 34333 34334 34335 34336 34337 34338 34339 34340 34341 34342 34343 34344 34345 34346 34347 34348 34349 34350 34351 34352 34353 34354 34355 34356 34357 34358 34359 34360 34361 34362 34363 34364 34365 34366 34367 34368 34369 34370 34371 34372 34373 34374 34375 34376 34377 34378 34379 34380 34381 34382 34383 34384 34385 34386 34387 34388 34389 34390 34391 34392 34393 34394 34395 34396 34397 34398 34399 34400 34401 34402 34403 34404 34405 34406 34407 34408 34409 34410 34411 34412 34413 34414 34415 34416 34417 34418 34419 34420 34421 34422 34423 34424 34425 34426 34427 34428 34429 34430 34431 34432 34433 34434 34435 34436 34437 34438 34439 34440 34441 34442 34443 34444 34445 34446 34447 34448 34449 34450 34451 34452 34453 34454 34455 34456 34457 34458 34459 34460 34461 34462 34463 34464 34465 34466 34467 34468 34469 34470 34471 34472 34473 34474 34475 34476 34477 34478 34479 34480 34481 34482 34483 34484 34485 34486 34487 34488 34489 34490 34491 34492 34493 34494 34495 34496 34497 34498 34499 34500 34501 34502 34503 34504 34505 34506 34507 34508 34509 34510 34511 34512 34513 34514 34515 34516 34517 34518 34519 34520 34521 34522 34523 34524 34525 34526 34527 34528 34529 34530 34531 34532 34533 34534 34535 34536 34537 34538 34539 34540 34541 34542 34543 34544 34545 34546 34547 34548 34549 34550 34551 34552 34553 34554 34555 34556 34557 34558 34559 34560 34561 34562 34563 34564 34565 34566 34567 34568 34569 34570 34571 34572 34573 34574 34575 34576 34577 34578 34579 34580 34581 34582 34583 34584 34585 34586 34587 34588 34589 34590 34591 34592 34593 34594 34595 34596 34597 34598 34599 34600 34601 34602 34603 34604 34605 34606 34607 34608 34609 34610 34611 34612 34613 34614 34615 34616 34617 34618 34619 34620 34621 34622 34623 34624 34625 34626 34627 34628 34629 34630 34631 34632 34633 34634 34635 34636 34637 34638 34639 34640 34641 34642 34643 34644 34645 34646 34647 34648 34649 34650 34651 34652 34653 34654 34655 34656 34657 34658 34659 34660 34661 34662 34663 34664 34665 34666 34667 34668 34669 34670 34671 34672 34673 34674 34675 34676 34677 34678 34679 34680 34681 34682 34683 34684 34685 34686 34687 34688 34689 34690 34691 34692 34693 34694 34695 34696 34697 34698 34699 34700 34701 34702 34703 34704 34705 34706 34707 34708 34709 34710 34711 34712 34713 34714 34715 34716 34717 34718 34719 34720 34721 34722 34723 34724 34725 34726 34727 34728 34729 34730 34731 34732 34733 34734 34735 34736 34737 34738 34739 34740 34741 34742 34743 34744 34745 34746 34747 34748 34749 34750 34751 34752 34753 34754 34755 34756 34757 34758 34759 34760 34761 34762 34763 34764 34765 34766 34767 34768 34769 34770 34771 34772 34773 34774 34775 34776 34777 34778 34779 34780 34781 34782 34783 34784 34785 34786 34787 34788 34789 34790 34791 34792 34793 34794 34795 34796 34797 34798 34799 34800 34801 34802 34803 34804 34805 34806 34807 34808 34809 34810 34811 34812 34813 34814 34815 34816 34817 34818 34819 34820 34821 34822 34823 34824 34825 34826 34827 34828 34829 34830 34831 34832 34833 34834 34835 34836 34837 34838 34839 34840 34841 34842 34843 34844 34845 34846 34847 34848 34849 34850 34851 34852 34853 34854 34855 34856 34857 34858 34859 34860 34861 34862 34863 34864 34865 34866 34867 34868 34869 34870 34871 34872 34873 34874 34875 34876 34877 34878 34879 34880 34881 34882 34883 34884 34885 34886 34887 34888 34889 34890 34891 34892 34893 34894 34895 34896 34897 34898 34899 34900 34901 34902 34903 34904 34905 34906 34907 34908 34909 34910 34911 34912 34913 34914 34915 34916 34917 34918 34919 34920 34921 34922 34923 34924 34925 34926 34927 34928 34929 34930 34931 34932 34933 34934 34935 34936 34937 34938 34939 34940 34941 34942 34943 34944 34945 34946 34947 34948 34949 34950 34951 34952 34953 34954 34955 34956 34957 34958 34959 34960 34961 34962 34963 34964 34965 34966 34967 34968 34969 34970 34971 34972 34973 34974 34975 34976 34977 34978 34979 34980 34981 34982 34983 34984 34985 34986 34987 34988 34989 34990 34991 34992 34993 34994 34995 34996 34997 34998 34999 35000 35001 35002 35003 35004 35005 35006 35007 35008 35009 35010 35011 35012 35013 35014 35015 35016 35017 35018 35019 35020 35021 35022 35023 35024 35025 35026 35027 35028 35029 35030 35031 35032 35033 35034 35035 35036 35037 35038 35039 35040 35041 35042 35043 35044 35045 35046 35047 35048 35049 35050 35051 35052 35053 35054 35055 35056 35057 35058 35059 35060 35061 35062 35063 35064 35065 35066 35067 35068 35069 35070 35071 35072 35073 35074 35075 35076 35077 35078 35079 35080 35081 35082 35083 35084 35085 35086 35087 35088 35089 35090 35091 35092 35093 35094 35095 35096 35097 35098 35099 35100 35101 35102 35103 35104 35105 35106 35107 35108 35109 35110 35111 35112 35113 35114 35115 35116 35117 35118 35119 35120 35121 35122 35123 35124 35125 35126 35127 35128 35129 35130 35131 35132 35133 35134 35135 35136 35137 35138 35139 35140 35141 35142 35143 35144 35145 35146 35147 35148 35149 35150 35151 35152 35153 35154 35155 35156 35157 35158 35159 35160 35161 35162 35163 35164 35165 35166 35167 35168 35169 35170 35171 35172 35173 35174 35175 35176 35177 35178 35179 35180 35181 35182 35183 35184 35185 35186 35187 35188 35189 35190 35191 35192 35193 35194 35195 35196 35197 35198 35199 35200 35201 35202 35203 35204 35205 35206 35207 35208 35209 35210 35211 35212 35213 35214 35215 35216 35217 35218 35219 35220 35221 35222 35223 35224 35225 35226 35227 35228 35229 35230 35231 35232 35233 35234 35235 35236 35237 35238 35239 35240 35241 35242 35243 35244 35245 35246 35247 35248 35249 35250 35251 35252 35253 35254 35255 35256 35257 35258 35259 35260 35261 35262 35263 35264 35265 35266 35267 35268 35269 35270 35271 35272 35273 35274 35275 35276 35277 35278 35279 35280 35281 35282 35283 35284 35285 35286 35287 35288 35289 35290 35291 35292 35293 35294 35295 35296 35297 35298 35299 35300 35301 35302 35303 35304 35305 35306 35307 35308 35309 35310 35311 35312 35313 35314 35315 35316 35317 35318 35319 35320 35321 35322 35323 35324 35325 35326 35327 35328 35329 35330 35331 35332 35333 35334 35335 35336 35337 35338 35339 35340 35341 35342 35343 35344 35345 35346 35347 35348 35349 35350 35351 35352 35353 35354 35355 35356 35357 35358 35359 35360 35361 35362 35363 35364 35365 35366 35367 35368 35369 35370 35371 35372 35373 35374 35375 35376 35377 35378 35379 35380 35381 35382 35383 35384 35385 35386 35387 35388 35389 35390 35391 35392 35393 35394 35395 35396 35397 35398 35399 35400 35401 35402 35403 35404 35405 35406 35407 35408 35409 35410 35411 35412 35413 35414 35415 35416 35417 35418 35419 35420 35421 35422 35423 35424 35425 35426 35427 35428 35429 35430 35431 35432 35433 35434 35435 35436 35437 35438 35439 35440 35441 35442 35443 35444 35445 35446 35447 35448 35449 35450 35451 35452 35453 35454 35455 35456 35457 35458 35459 35460 35461 35462 35463 35464 35465 35466 35467 35468 35469 35470 35471 35472 35473 35474 35475 35476 35477 35478 35479 35480 35481 35482 35483 35484 35485 35486 35487 35488 35489 35490 35491 35492 35493 35494 35495 35496 35497 35498 35499 35500 35501 35502 35503 35504 35505 35506 35507 35508 35509 35510 35511 35512 35513 35514 35515 35516 35517 35518 35519 35520 35521 35522 35523 35524 35525 35526 35527 35528 35529 35530 35531 35532 35533 35534 35535 35536 35537 35538 35539 35540 35541 35542 35543 35544 35545 35546 35547 35548 35549 35550 35551 35552 35553 35554 35555 35556 35557 35558 35559 35560 35561 35562 35563 35564 35565 35566 35567 35568 35569 35570 35571 35572 35573 35574 35575 35576 35577 35578 35579 35580 35581 35582 35583 35584 35585 35586 35587 35588 35589 35590 35591 35592 35593 35594 35595 35596 35597 35598 35599 35600 35601 35602 35603 35604 35605 35606 35607 35608 35609 35610 35611 35612 35613 35614 35615 35616 35617 35618 35619 35620 35621 35622 35623 35624 35625 35626 35627 35628 35629 35630 35631 35632 35633 35634 35635 35636 35637 35638 35639 35640 35641 35642 35643 35644 35645 35646 35647 35648 35649 35650 35651 35652 35653 35654 35655 35656 35657 35658 35659 35660 35661 35662 35663 35664 35665 35666 35667 35668 35669 35670 35671 35672 35673 35674 35675 35676 35677 35678 35679 35680 35681 35682 35683 35684 35685 35686 35687 35688 35689 35690 35691 35692 35693 35694 35695 35696 35697 35698 35699 35700 35701 35702 35703 35704 35705 35706 35707 35708 35709 35710 35711 35712 35713 35714 35715 35716 35717 35718 35719 35720 35721 35722 35723 35724 35725 35726 35727 35728 35729 35730 35731 35732 35733 35734 35735 35736 35737 35738 35739 35740 35741 35742 35743 35744 35745 35746 35747 35748 35749 35750 35751 35752 35753 35754 35755 35756 35757 35758 35759 35760 35761 35762 35763 35764 35765 35766 35767 35768 35769 35770 35771 35772 35773 35774 35775 35776 35777 35778 35779 35780 35781 35782 35783 35784 35785 35786 35787 35788 35789 35790 35791 35792 35793 35794 35795 35796 35797 35798 35799 35800 35801 35802 35803 35804 35805 35806 35807 35808 35809 35810 35811 35812 35813 35814 35815 35816 35817 35818 35819 35820 35821 35822 35823 35824 35825 35826 35827 35828 35829 35830 35831 35832 35833 35834 35835 35836 35837 35838 35839 35840 35841 35842 35843 35844 35845 35846 35847 35848 35849 35850 35851 35852 35853 35854 35855 35856 35857 35858 35859 35860 35861 35862 35863 35864 35865 35866 35867 35868 35869 35870 35871 35872 35873 35874 35875 35876 35877 35878 35879 35880 35881 35882 35883 35884 35885 35886 35887 35888 35889 35890 35891 35892 35893 35894 35895 35896 35897 35898 35899 35900 35901 35902 35903 35904 35905 35906 35907 35908 35909 35910 35911 35912 35913 35914 35915 35916 35917 35918 35919 35920 35921 35922 35923 35924 35925 35926 35927 35928 35929 35930 35931 35932 35933 35934 35935 35936 35937 35938 35939 35940 35941 35942 35943 35944 35945 35946 35947 35948 35949 35950 35951 35952 35953 35954 35955 35956 35957 35958 35959 35960 35961 35962 35963 35964 35965 35966 35967 35968 35969 35970 35971 35972 35973 35974 35975 35976 35977 35978 35979 35980 35981 35982 35983 35984 35985 35986 35987 35988 35989 35990 35991 35992 35993 35994 35995 35996 35997 35998 35999 36000 36001 36002 36003 36004 36005 36006 36007 36008 36009 36010 36011 36012 36013 36014 36015 36016 36017 36018 36019 36020 36021 36022 36023 36024 36025 36026 36027 36028 36029 36030 36031 36032 36033 36034 36035 36036 36037 36038 36039 36040 36041 36042 36043 36044 36045 36046 36047 36048 36049 36050 36051 36052 36053 36054 36055 36056 36057 36058 36059 36060 36061 36062 36063 36064 36065 36066 36067 36068 36069 36070 36071 36072 36073 36074 36075 36076 36077 36078 36079 36080 36081 36082 36083 36084 36085 36086 36087 36088 36089 36090 36091 36092 36093 36094 36095 36096 36097 36098 36099 36100 36101 36102 36103 36104 36105 36106 36107 36108 36109 36110 36111 36112 36113 36114 36115 36116 36117 36118 36119 36120 36121 36122 36123 36124 36125 36126 36127 36128 36129 36130 36131 36132 36133 36134 36135 36136 36137 36138 36139 36140 36141 36142 36143 36144 36145 36146 36147 36148 36149 36150 36151 36152 36153 36154 36155 36156 36157 36158 36159 36160 36161 36162 36163 36164 36165 36166 36167 36168 36169 36170 36171 36172 36173 36174 36175 36176 36177 36178 36179 36180 36181 36182 36183 36184 36185 36186 36187 36188 36189 36190 36191 36192 36193 36194 36195 36196 36197 36198 36199 36200 36201 36202 36203 36204 36205 36206 36207 36208 36209 36210 36211 36212 36213 36214 36215 36216 36217 36218 36219 36220 36221 36222 36223 36224 36225 36226 36227 36228 36229 36230 36231 36232 36233 36234 36235 36236 36237 36238 36239 36240 36241 36242 36243 36244 36245 36246 36247 36248 36249 36250 36251 36252 36253 36254 36255 36256 36257 36258 36259 36260 36261 36262 36263 36264 36265 36266 36267 36268 36269 36270 36271 36272 36273 36274 36275 36276 36277 36278 36279 36280 36281 36282 36283 36284 36285 36286 36287 36288 36289 36290 36291 36292 36293 36294 36295 36296 36297 36298 36299 36300 36301 36302 36303 36304 36305 36306 36307 36308 36309 36310 36311 36312 36313 36314 36315 36316 36317 36318 36319 36320 36321 36322 36323 36324 36325 36326 36327 36328 36329 36330 36331 36332 36333 36334 36335 36336 36337 36338 36339 36340 36341 36342 36343 36344 36345 36346 36347 36348 36349 36350 36351 36352 36353 36354 36355 36356 36357 36358 36359 36360 36361 36362 36363 36364 36365 36366 36367 36368 36369 36370 36371 36372 36373 36374 36375 36376 36377 36378 36379 36380 36381 36382 36383 36384 36385 36386 36387 36388 36389 36390 36391 36392 36393 36394 36395 36396 36397 36398 36399 36400 36401 36402 36403 36404 36405 36406 36407 36408 36409 36410 36411 36412 36413 36414 36415 36416 36417 36418 36419 36420 36421 36422 36423 36424 36425 36426 36427 36428 36429 36430 36431 36432 36433 36434 36435 36436 36437 36438 36439 36440 36441 36442 36443 36444 36445 36446 36447 36448 36449 36450 36451 36452 36453 36454 36455 36456 36457 36458 36459 36460 36461 36462 36463 36464 36465 36466 36467 36468 36469 36470 36471 36472 36473 36474 36475 36476 36477 36478 36479 36480 36481 36482 36483 36484 36485 36486 36487 36488 36489 36490 36491 36492 36493 36494 36495 36496 36497 36498 36499 36500 36501 36502 36503 36504 36505 36506 36507 36508 36509 36510 36511 36512 36513 36514 36515 36516 36517 36518 36519 36520 36521 36522 36523 36524 36525 36526 36527 36528 36529 36530 36531 36532 36533 36534 36535 36536 36537 36538 36539 36540 36541 36542 36543 36544 36545 36546 36547 36548 36549 36550 36551 36552 36553 36554 36555 36556 36557 36558 36559 36560 36561 36562 36563 36564 36565 36566 36567 36568 36569 36570 36571 36572 36573 36574 36575 36576 36577 36578 36579 36580 36581 36582 36583 36584 36585 36586 36587 36588 36589 36590 36591 36592 36593 36594 36595 36596 36597 36598 36599 36600 36601 36602 36603 36604 36605 36606 36607 36608 36609 36610 36611 36612 36613 36614 36615 36616 36617 36618 36619 36620 36621 36622 36623 36624 36625 36626 36627 36628 36629 36630 36631 36632 36633 36634 36635 36636 36637 36638 36639 36640 36641 36642 36643 36644 36645 36646 36647 36648 36649 36650 36651 36652 36653 36654 36655 36656 36657 36658 36659 36660 36661 36662 36663 36664 36665 36666 36667 36668 36669 36670 36671 36672 36673 36674 36675 36676 36677 36678 36679 36680 36681 36682 36683 36684 36685 36686 36687 36688 36689 36690 36691 36692 36693 36694 36695 36696 36697 36698 36699 36700 36701 36702 36703 36704 36705 36706 36707 36708 36709 36710 36711 36712 36713 36714 36715 36716 36717 36718 36719 36720 36721 36722 36723 36724 36725 36726 36727 36728 36729 36730 36731 36732 36733 36734 36735 36736 36737 36738 36739 36740 36741 36742 36743 36744 36745 36746 36747 36748 36749 36750 36751 36752 36753 36754 36755 36756 36757 36758 36759 36760 36761 36762 36763 36764 36765 36766 36767 36768 36769 36770 36771 36772 36773 36774 36775 36776 36777 36778 36779 36780 36781 36782 36783 36784 36785 36786 36787 36788 36789 36790 36791 36792 36793 36794 36795 36796 36797 36798 36799 36800 36801 36802 36803 36804 36805 36806 36807 36808 36809 36810 36811 36812 36813 36814 36815 36816 36817 36818 36819 36820 36821 36822 36823 36824 36825 36826 36827 36828 36829 36830 36831 36832 36833 36834 36835 36836 36837 36838 36839 36840 36841 36842 36843 36844 36845 36846 36847 36848 36849 36850 36851 36852 36853 36854 36855 36856 36857 36858 36859 36860 36861 36862 36863 36864 36865 36866 36867 36868 36869 36870 36871 36872 36873 36874 36875 36876 36877 36878 36879 36880 36881 36882 36883 36884 36885 36886 36887 36888 36889 36890 36891 36892 36893 36894 36895 36896 36897 36898 36899 36900 36901 36902 36903 36904 36905 36906 36907 36908 36909 36910 36911 36912 36913 36914 36915 36916 36917 36918 36919 36920 36921 36922 36923 36924 36925 36926 36927 36928 36929 36930 36931 36932 36933 36934 36935 36936 36937 36938 36939 36940 36941 36942 36943 36944 36945 36946 36947 36948 36949 36950 36951 36952 36953 36954 36955 36956 36957 36958 36959 36960 36961 36962 36963 36964 36965 36966 36967 36968 36969 36970 36971 36972 36973 36974 36975 36976 36977 36978 36979 36980 36981 36982 36983 36984 36985 36986 36987 36988 36989 36990 36991 36992 36993 36994 36995 36996 36997 36998 36999 37000 37001 37002 37003 37004 37005 37006 37007 37008 37009 37010 37011 37012 37013 37014 37015 37016 37017 37018 37019 37020 37021 37022 37023 37024 37025 37026 37027 37028 37029 37030 37031 37032 37033 37034 37035 37036 37037 37038 37039 37040 37041 37042 37043 37044 37045 37046 37047 37048 37049 37050 37051 37052 37053 37054 37055 37056 37057 37058 37059 37060 37061 37062 37063 37064 37065 37066 37067 37068 37069 37070 37071 37072 37073 37074 37075 37076 37077 37078 37079 37080 37081 37082 37083 37084 37085 37086 37087 37088 37089 37090 37091 37092 37093 37094 37095 37096 37097 37098 37099 37100 37101 37102 37103 37104 37105 37106 37107 37108 37109 37110 37111 37112 37113 37114 37115 37116 37117 37118 37119 37120 37121 37122 37123 37124 37125 37126 37127 37128 37129 37130 37131 37132 37133 37134 37135 37136 37137 37138 37139 37140 37141 37142 37143 37144 37145 37146 37147 37148 37149 37150 37151 37152 37153 37154 37155 37156 37157 37158 37159 37160 37161 37162 37163 37164 37165 37166 37167 37168 37169 37170 37171 37172 37173 37174 37175 37176 37177 37178 37179 37180 37181 37182 37183 37184 37185 37186 37187 37188 37189 37190 37191 37192 37193 37194 37195 37196 37197 37198 37199 37200 37201 37202 37203 37204 37205 37206 37207 37208 37209 37210 37211 37212 37213 37214 37215 37216 37217 37218 37219 37220 37221 37222 37223 37224 37225 37226 37227 37228 37229 37230 37231 37232 37233 37234 37235 37236 37237 37238 37239 37240 37241 37242 37243 37244 37245 37246 37247 37248 37249 37250 37251 37252 37253 37254 37255 37256 37257 37258 37259 37260 37261 37262 37263 37264 37265 37266 37267 37268 37269 37270 37271 37272 37273 37274 37275 37276 37277 37278 37279 37280 37281 37282 37283 37284 37285 37286 37287 37288 37289 37290 37291 37292 37293 37294 37295 37296 37297 37298 37299 37300 37301 37302 37303 37304 37305 37306 37307 37308 37309 37310 37311 37312 37313 37314 37315 37316 37317 37318 37319 37320 37321 37322 37323 37324 37325 37326 37327 37328 37329 37330 37331 37332 37333 37334 37335 37336 37337 37338 37339 37340 37341 37342 37343 37344 37345 37346 37347 37348 37349 37350 37351 37352 37353 37354 37355 37356 37357 37358 37359 37360 37361 37362 37363 37364 37365 37366 37367 37368 37369 37370 37371 37372 37373 37374 37375 37376 37377 37378 37379 37380 37381 37382 37383 37384 37385 37386 37387 37388 37389 37390 37391 37392 37393 37394 37395 37396 37397 37398 37399 37400 37401 37402 37403 37404 37405 37406 37407 37408 37409 37410 37411 37412 37413 37414 37415 37416 37417 37418 37419 37420 37421 37422 37423 37424 37425 37426 37427 37428 37429 37430 37431 37432 37433 37434 37435 37436 37437 37438 37439 37440 37441 37442 37443 37444 37445 37446 37447 37448 37449 37450 37451 37452 37453 37454 37455 37456 37457 37458 37459 37460 37461 37462 37463 37464 37465 37466 37467 37468 37469 37470 37471 37472 37473 37474 37475 37476 37477 37478 37479 37480 37481 37482 37483 37484 37485 37486 37487 37488 37489 37490 37491 37492 37493 37494 37495 37496 37497 37498 37499 37500 37501 37502 37503 37504 37505 37506 37507 37508 37509 37510 37511 37512 37513 37514 37515 37516 37517 37518 37519 37520 37521 37522 37523 37524 37525 37526 37527 37528 37529 37530 37531 37532 37533 37534 37535 37536 37537 37538 37539 37540 37541 37542 37543 37544 37545 37546 37547 37548 37549 37550 37551 37552 37553 37554 37555 37556 37557 37558 37559 37560 37561 37562 37563 37564 37565 37566 37567 37568 37569 37570 37571 37572 37573 37574 37575 37576 37577 37578 37579 37580 37581 37582 37583 37584 37585 37586 37587 37588 37589 37590 37591 37592 37593 37594 37595 37596 37597 37598 37599 37600 37601 37602 37603 37604 37605 37606 37607 37608 37609 37610 37611 37612 37613 37614 37615 37616 37617 37618 37619 37620 37621 37622 37623 37624 37625 37626 37627 37628 37629 37630 37631 37632 37633 37634 37635 37636 37637 37638 37639 37640 37641 37642 37643 37644 37645 37646 37647 37648 37649 37650 37651 37652 37653 37654 37655 37656 37657 37658 37659 37660 37661 37662 37663 37664 37665 37666 37667 37668 37669 37670 37671 37672 37673 37674 37675 37676 37677 37678 37679 37680 37681 37682 37683 37684 37685 37686 37687 37688 37689 37690 37691 37692 37693 37694 37695 37696 37697 37698 37699 37700 37701 37702 37703 37704 37705 37706 37707 37708 37709 37710 37711 37712 37713 37714 37715 37716 37717 37718 37719 37720 37721 37722 37723 37724 37725 37726 37727 37728 37729 37730 37731 37732 37733 37734 37735 37736 37737 37738 37739 37740 37741 37742 37743 37744 37745 37746 37747 37748 37749 37750 37751 37752 37753 37754 37755 37756 37757 37758 37759 37760 37761 37762 37763 37764 37765 37766 37767 37768 37769 37770 37771 37772 37773 37774 37775 37776 37777 37778 37779 37780 37781 37782 37783 37784 37785 37786 37787 37788 37789 37790 37791 37792 37793 37794 37795 37796 37797 37798 37799 37800 37801 37802 37803 37804 37805 37806 37807 37808 37809 37810 37811 37812 37813 37814 37815 37816 37817 37818 37819 37820 37821 37822 37823 37824 37825 37826 37827 37828 37829 37830 37831 37832 37833 37834 37835 37836 37837 37838 37839 37840 37841 37842 37843 37844 37845 37846 37847 37848 37849 37850 37851 37852 37853 37854 37855 37856 37857 37858 37859 37860 37861 37862 37863 37864 37865 37866 37867 37868 37869 37870 37871 37872 37873 37874 37875 37876 37877 37878 37879 37880 37881 37882 37883 37884 37885 37886 37887 37888 37889 37890 37891 37892 37893 37894 37895 37896 37897 37898 37899 37900 37901 37902 37903 37904 37905 37906 37907 37908 37909 37910 37911 37912 37913 37914 37915 37916 37917 37918 37919 37920 37921 37922 37923 37924 37925 37926 37927 37928 37929 37930 37931 37932 37933 37934 37935 37936 37937 37938 37939 37940 37941 37942 37943 37944 37945 37946 37947 37948 37949 37950 37951 37952 37953 37954 37955 37956 37957 37958 37959 37960 37961 37962 37963 37964 37965 37966 37967 37968 37969 37970 37971 37972 37973 37974 37975 37976 37977 37978 37979 37980 37981 37982 37983 37984 37985 37986 37987 37988 37989 37990 37991 37992 37993 37994 37995 37996 37997 37998 37999 38000 38001 38002 38003 38004 38005 38006 38007 38008 38009 38010 38011 38012 38013 38014 38015 38016 38017 38018 38019 38020 38021 38022 38023 38024 38025 38026 38027 38028 38029 38030 38031 38032 38033 38034 38035 38036 38037 38038 38039 38040 38041 38042 38043 38044 38045 38046 38047 38048 38049 38050 38051 38052 38053 38054 38055 38056 38057 38058 38059 38060 38061 38062 38063 38064 38065 38066 38067 38068 38069 38070 38071 38072 38073 38074 38075 38076 38077 38078 38079 38080 38081 38082 38083 38084 38085 38086 38087 38088 38089 38090 38091 38092 38093 38094 38095 38096 38097 38098 38099 38100 38101 38102 38103 38104 38105 38106 38107 38108 38109 38110 38111 38112 38113 38114 38115 38116 38117 38118 38119 38120 38121 38122 38123 38124 38125 38126 38127 38128 38129 38130 38131 38132 38133 38134 38135 38136 38137 38138 38139 38140 38141 38142 38143 38144 38145 38146 38147 38148 38149 38150 38151 38152 38153 38154 38155 38156 38157 38158 38159 38160 38161 38162 38163 38164 38165 38166 38167 38168 38169 38170 38171 38172 38173 38174 38175 38176 38177 38178 38179 38180 38181 38182 38183 38184 38185 38186 38187 38188 38189 38190 38191 38192 38193 38194 38195 38196 38197 38198 38199 38200 38201 38202 38203 38204 38205 38206 38207 38208 38209                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
var toPropertyKey = require("./toPropertyKey.js");
function _defineProperty(e, r, t) {
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
    value: t,
    enumerable: !0,
    configurable: !0,
    writable: !0
  }) : e[r] = t, e;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./toPropertyKey.js":4}],2:[function(require,module,exports){
function _interopRequireDefault(e) {
  return e && e.__esModule ? e : {
    "default": e
  };
}
module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],3:[function(require,module,exports){
var _typeof = require("./typeof.js")["default"];
function toPrimitive(t, r) {
  if ("object" != _typeof(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r || "default");
    if ("object" != _typeof(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}
module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./typeof.js":5}],4:[function(require,module,exports){
var _typeof = require("./typeof.js")["default"];
var toPrimitive = require("./toPrimitive.js");
function toPropertyKey(t) {
  var i = toPrimitive(t, "string");
  return "symbol" == _typeof(i) ? i : i + "";
}
module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./toPrimitive.js":3,"./typeof.js":5}],5:[function(require,module,exports){
function _typeof(o) {
  "@babel/helpers - typeof";
 
  return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
    return typeof o;
  } : function (o) {
    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],6:[function(require,module,exports){
 
/**
 * Expose `Emitter`.
 */
 
exports.Emitter = Emitter;
 
/**
 * Initialize a new `Emitter`.
 *
 * @api public
 */
 
function Emitter(obj) {
  if (obj) return mixin(obj);
}
 
/**
 * Mixin the emitter properties.
 *
 * @param {Object} obj
 * @return {Object}
 * @api private
 */
 
function mixin(obj) {
  for (var key in Emitter.prototype) {
    obj[key] = Emitter.prototype[key];
  }
  return obj;
}
 
/**
 * Listen on the given `event` with `fn`.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */
 
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
  this._callbacks = this._callbacks || {};
  (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
    .push(fn);
  return this;
};
 
/**
 * Adds an `event` listener that will be invoked a single
 * time then automatically removed.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */
 
Emitter.prototype.once = function(event, fn){
  function on() {
    this.off(event, on);
    fn.apply(this, arguments);
  }
 
  on.fn = fn;
  this.on(event, on);
  return this;
};
 
/**
 * Remove the given callback for `event` or all
 * registered callbacks.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */
 
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
  this._callbacks = this._callbacks || {};
 
  // all
  if (0 == arguments.length) {
    this._callbacks = {};
    return this;
  }
 
  // specific event
  var callbacks = this._callbacks['$' + event];
  if (!callbacks) return this;
 
  // remove all handlers
  if (1 == arguments.length) {
    delete this._callbacks['$' + event];
    return this;
  }
 
  // remove specific handler
  var cb;
  for (var i = 0; i < callbacks.length; i++) {
    cb = callbacks[i];
    if (cb === fn || cb.fn === fn) {
      callbacks.splice(i, 1);
      break;
    }
  }
 
  // Remove event specific arrays for event types that no
  // one is subscribed for to avoid memory leak.
  if (callbacks.length === 0) {
    delete this._callbacks['$' + event];
  }
 
  return this;
};
 
/**
 * Emit `event` with the given args.
 *
 * @param {String} event
 * @param {Mixed} ...
 * @return {Emitter}
 */
 
Emitter.prototype.emit = function(event){
  this._callbacks = this._callbacks || {};
 
  var args = new Array(arguments.length - 1)
    , callbacks = this._callbacks['$' + event];
 
  for (var i = 1; i < arguments.length; i++) {
    args[i - 1] = arguments[i];
  }
 
  if (callbacks) {
    callbacks = callbacks.slice(0);
    for (var i = 0, len = callbacks.length; i < len; ++i) {
      callbacks[i].apply(this, args);
    }
  }
 
  return this;
};
 
// alias used for reserved events (protected method)
Emitter.prototype.emitReserved = Emitter.prototype.emit;
 
/**
 * Return array of callbacks for `event`.
 *
 * @param {String} event
 * @return {Array}
 * @api public
 */
 
Emitter.prototype.listeners = function(event){
  this._callbacks = this._callbacks || {};
  return this._callbacks['$' + event] || [];
};
 
/**
 * Check if this emitter has `event` handlers.
 *
 * @param {String} event
 * @return {Boolean}
 * @api public
 */
 
Emitter.prototype.hasListeners = function(event){
  return !! this.listeners(event).length;
};
 
},{}],7:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasCORS = void 0;
// imported from https://github.com/component/has-cors
let value = false;
try {
    value = typeof XMLHttpRequest !== 'undefined' &&
        'withCredentials' in new XMLHttpRequest();
}
catch (err) {
    // if XMLHttp support is disabled in IE then it will throw
    // when trying to create
}
exports.hasCORS = value;
 
},{}],8:[function(require,module,exports){
"use strict";
// imported from https://github.com/galkn/querystring
/**
 * Compiles a querystring
 * Returns string representation of the object
 *
 * @param {Object}
 * @api private
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.encode = encode;
exports.decode = decode;
function encode(obj) {
    let str = '';
    for (let i in obj) {
        if (obj.hasOwnProperty(i)) {
            if (str.length)
                str += '&';
            str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
        }
    }
    return str;
}
/**
 * Parses a simple querystring into an object
 *
 * @param {String} qs
 * @api private
 */
function decode(qs) {
    let qry = {};
    let pairs = qs.split('&');
    for (let i = 0, l = pairs.length; i < l; i++) {
        let pair = pairs[i].split('=');
        qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    return qry;
}
 
},{}],9:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = parse;
// imported from https://github.com/galkn/parseuri
/**
 * Parses a URI
 *
 * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
 *
 * See:
 * - https://developer.mozilla.org/en-US/docs/Web/API/URL
 * - https://caniuse.com/url
 * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
 *
 * History of the parse() method:
 * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
 * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
 * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
 *
 * @author Steven Levithan <stevenlevithan.com> (MIT license)
 * @api private
 */
const re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
const parts = [
    'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
];
function parse(str) {
    if (str.length > 8000) {
        throw "URI too long";
    }
    const src = str, b = str.indexOf('['), e = str.indexOf(']');
    if (b != -1 && e != -1) {
        str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
    }
    let m = re.exec(str || ''), uri = {}, i = 14;
    while (i--) {
        uri[parts[i]] = m[i] || '';
    }
    if (b != -1 && e != -1) {
        uri.source = src;
        uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
        uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
        uri.ipv6uri = true;
    }
    uri.pathNames = pathNames(uri, uri['path']);
    uri.queryKey = queryKey(uri, uri['query']);
    return uri;
}
function pathNames(obj, path) {
    const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
    if (path.slice(0, 1) == '/' || path.length === 0) {
        names.splice(0, 1);
    }
    if (path.slice(-1) == '/') {
        names.splice(names.length - 1, 1);
    }
    return names;
}
function queryKey(uri, query) {
    const data = {};
    query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
        if ($1) {
            data[$1] = $2;
        }
    });
    return data;
}
 
},{}],10:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultBinaryType = exports.globalThisShim = exports.nextTick = void 0;
exports.createCookieJar = createCookieJar;
exports.nextTick = (() => {
    const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
    if (isPromiseAvailable) {
        return (cb) => Promise.resolve().then(cb);
    }
    else {
        return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
    }
})();
exports.globalThisShim = (() => {
    if (typeof self !== "undefined") {
        return self;
    }
    else if (typeof window !== "undefined") {
        return window;
    }
    else {
        return Function("return this")();
    }
})();
exports.defaultBinaryType = "arraybuffer";
function createCookieJar() { }
 
},{}],11:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebTransport = exports.WebSocket = exports.NodeWebSocket = exports.XHR = exports.NodeXHR = exports.Fetch = exports.nextTick = exports.parse = exports.installTimerFunctions = exports.transports = exports.TransportError = exports.Transport = exports.protocol = exports.SocketWithUpgrade = exports.SocketWithoutUpgrade = exports.Socket = void 0;
const socket_js_1 = require("./socket.js");
Object.defineProperty(exports, "Socket", { enumerable: true, get: function () { return socket_js_1.Socket; } });
var socket_js_2 = require("./socket.js");
Object.defineProperty(exports, "SocketWithoutUpgrade", { enumerable: true, get: function () { return socket_js_2.SocketWithoutUpgrade; } });
Object.defineProperty(exports, "SocketWithUpgrade", { enumerable: true, get: function () { return socket_js_2.SocketWithUpgrade; } });
exports.protocol = socket_js_1.Socket.protocol;
var transport_js_1 = require("./transport.js");
Object.defineProperty(exports, "Transport", { enumerable: true, get: function () { return transport_js_1.Transport; } });
Object.defineProperty(exports, "TransportError", { enumerable: true, get: function () { return transport_js_1.TransportError; } });
var index_js_1 = require("./transports/index.js");
Object.defineProperty(exports, "transports", { enumerable: true, get: function () { return index_js_1.transports; } });
var util_js_1 = require("./util.js");
Object.defineProperty(exports, "installTimerFunctions", { enumerable: true, get: function () { return util_js_1.installTimerFunctions; } });
var parseuri_js_1 = require("./contrib/parseuri.js");
Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parseuri_js_1.parse; } });
var globals_node_js_1 = require("./globals.node.js");
Object.defineProperty(exports, "nextTick", { enumerable: true, get: function () { return globals_node_js_1.nextTick; } });
var polling_fetch_js_1 = require("./transports/polling-fetch.js");
Object.defineProperty(exports, "Fetch", { enumerable: true, get: function () { return polling_fetch_js_1.Fetch; } });
var polling_xhr_node_js_1 = require("./transports/polling-xhr.node.js");
Object.defineProperty(exports, "NodeXHR", { enumerable: true, get: function () { return polling_xhr_node_js_1.XHR; } });
var polling_xhr_js_1 = require("./transports/polling-xhr.js");
Object.defineProperty(exports, "XHR", { enumerable: true, get: function () { return polling_xhr_js_1.XHR; } });
var websocket_node_js_1 = require("./transports/websocket.node.js");
Object.defineProperty(exports, "NodeWebSocket", { enumerable: true, get: function () { return websocket_node_js_1.WS; } });
var websocket_js_1 = require("./transports/websocket.js");
Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function () { return websocket_js_1.WS; } });
var webtransport_js_1 = require("./transports/webtransport.js");
Object.defineProperty(exports, "WebTransport", { enumerable: true, get: function () { return webtransport_js_1.WT; } });
 
},{"./contrib/parseuri.js":9,"./globals.node.js":10,"./socket.js":12,"./transport.js":13,"./transports/index.js":14,"./transports/polling-fetch.js":15,"./transports/polling-xhr.js":16,"./transports/polling-xhr.node.js":16,"./transports/websocket.js":18,"./transports/websocket.node.js":18,"./transports/webtransport.js":19,"./util.js":20}],12:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Socket = exports.SocketWithUpgrade = exports.SocketWithoutUpgrade = void 0;
const index_js_1 = require("./transports/index.js");
const util_js_1 = require("./util.js");
const parseqs_js_1 = require("./contrib/parseqs.js");
const parseuri_js_1 = require("./contrib/parseuri.js");
const component_emitter_1 = require("@socket.io/component-emitter");
const engine_io_parser_1 = require("engine.io-parser");
const globals_node_js_1 = require("./globals.node.js");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("engine.io-client:socket"); // debug()
const withEventListeners = typeof addEventListener === "function" &&
    typeof removeEventListener === "function";
const OFFLINE_EVENT_LISTENERS = [];
if (withEventListeners) {
    // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the
    // script, so we create one single event listener here which will forward the event to the socket instances
    addEventListener("offline", () => {
        debug("closing %d connection(s) because the network was lost", OFFLINE_EVENT_LISTENERS.length);
        OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
    }, false);
}
/**
 * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
 * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
 *
 * This class comes without upgrade mechanism, which means that it will keep the first low-level transport that
 * successfully establishes the connection.
 *
 * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
 *
 * @example
 * import { SocketWithoutUpgrade, WebSocket } from "engine.io-client";
 *
 * const socket = new SocketWithoutUpgrade({
 *   transports: [WebSocket]
 * });
 *
 * socket.on("open", () => {
 *   socket.send("hello");
 * });
 *
 * @see SocketWithUpgrade
 * @see Socket
 */
class SocketWithoutUpgrade extends component_emitter_1.Emitter {
    /**
     * Socket constructor.
     *
     * @param {String|Object} uri - uri or options
     * @param {Object} opts - options
     */
    constructor(uri, opts) {
        super();
        this.binaryType = globals_node_js_1.defaultBinaryType;
        this.writeBuffer = [];
        this._prevBufferLen = 0;
        this._pingInterval = -1;
        this._pingTimeout = -1;
        this._maxPayload = -1;
        /**
         * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the
         * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.
         */
        this._pingTimeoutTime = Infinity;
        if (uri && "object" === typeof uri) {
            opts = uri;
            uri = null;
        }
        if (uri) {
            const parsedUri = (0, parseuri_js_1.parse)(uri);
            opts.hostname = parsedUri.host;
            opts.secure =
                parsedUri.protocol === "https" || parsedUri.protocol === "wss";
            opts.port = parsedUri.port;
            if (parsedUri.query)
                opts.query = parsedUri.query;
        }
        else if (opts.host) {
            opts.hostname = (0, parseuri_js_1.parse)(opts.host).host;
        }
        (0, util_js_1.installTimerFunctions)(this, opts);
        this.secure =
            null != opts.secure
                ? opts.secure
                : typeof location !== "undefined" && "https:" === location.protocol;
        if (opts.hostname && !opts.port) {
            // if no port is specified manually, use the protocol default
            opts.port = this.secure ? "443" : "80";
        }
        this.hostname =
            opts.hostname ||
                (typeof location !== "undefined" ? location.hostname : "localhost");
        this.port =
            opts.port ||
                (typeof location !== "undefined" && location.port
                    ? location.port
                    : this.secure
                        ? "443"
                        : "80");
        this.transports = [];
        this._transportsByName = {};
        opts.transports.forEach((t) => {
            const transportName = t.prototype.name;
            this.transports.push(transportName);
            this._transportsByName[transportName] = t;
        });
        this.opts = Object.assign({
            path: "/engine.io",
            agent: false,
            withCredentials: false,
            upgrade: true,
            timestampParam: "t",
            rememberUpgrade: false,
            addTrailingSlash: true,
            rejectUnauthorized: true,
            perMessageDeflate: {
                threshold: 1024,
            },
            transportOptions: {},
            closeOnBeforeunload: false,
        }, opts);
        this.opts.path =
            this.opts.path.replace(/\/$/, "") +
                (this.opts.addTrailingSlash ? "/" : "");
        if (typeof this.opts.query === "string") {
            this.opts.query = (0, parseqs_js_1.decode)(this.opts.query);
        }
        if (withEventListeners) {
            if (this.opts.closeOnBeforeunload) {
                // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
                // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
                // closed/reloaded)
                this._beforeunloadEventListener = () => {
                    if (this.transport) {
                        // silently close the transport
                        this.transport.removeAllListeners();
                        this.transport.close();
                    }
                };
                addEventListener("beforeunload", this._beforeunloadEventListener, false);
            }
            if (this.hostname !== "localhost") {
                debug("adding listener for the 'offline' event");
                this._offlineEventListener = () => {
                    this._onClose("transport close", {
                        description: "network connection lost",
                    });
                };
                OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
            }
        }
        if (this.opts.withCredentials) {
            this._cookieJar = (0, globals_node_js_1.createCookieJar)();
        }
        this._open();
    }
    /**
     * Creates transport of the given type.
     *
     * @param {String} name - transport name
     * @return {Transport}
     * @private
     */
    createTransport(name) {
        debug('creating transport "%s"', name);
        const query = Object.assign({}, this.opts.query);
        // append engine.io protocol identifier
        query.EIO = engine_io_parser_1.protocol;
        // transport name
        query.transport = name;
        // session id if we already have one
        if (this.id)
            query.sid = this.id;
        const opts = Object.assign({}, this.opts, {
            query,
            socket: this,
            hostname: this.hostname,
            secure: this.secure,
            port: this.port,
        }, this.opts.transportOptions[name]);
        debug("options: %j", opts);
        return new this._transportsByName[name](opts);
    }
    /**
     * Initializes transport to use and starts probe.
     *
     * @private
     */
    _open() {
        if (this.transports.length === 0) {
            // Emit error on next tick so it can be listened to
            this.setTimeoutFn(() => {
                this.emitReserved("error", "No transports available");
            }, 0);
            return;
        }
        const transportName = this.opts.rememberUpgrade &&
            SocketWithoutUpgrade.priorWebsocketSuccess &&
            this.transports.indexOf("websocket") !== -1
            ? "websocket"
            : this.transports[0];
        this.readyState = "opening";
        const transport = this.createTransport(transportName);
        transport.open();
        this.setTransport(transport);
    }
    /**
     * Sets the current transport. Disables the existing one (if any).
     *
     * @private
     */
    setTransport(transport) {
        debug("setting transport %s", transport.name);
        if (this.transport) {
            debug("clearing existing transport %s", this.transport.name);
            this.transport.removeAllListeners();
        }
        // set up transport
        this.transport = transport;
        // set up transport listeners
        transport
            .on("drain", this._onDrain.bind(this))
            .on("packet", this._onPacket.bind(this))
            .on("error", this._onError.bind(this))
            .on("close", (reason) => this._onClose("transport close", reason));
    }
    /**
     * Called when connection is deemed open.
     *
     * @private
     */
    onOpen() {
        debug("socket open");
        this.readyState = "open";
        SocketWithoutUpgrade.priorWebsocketSuccess =
            "websocket" === this.transport.name;
        this.emitReserved("open");
        this.flush();
    }
    /**
     * Handles a packet.
     *
     * @private
     */
    _onPacket(packet) {
        if ("opening" === this.readyState ||
            "open" === this.readyState ||
            "closing" === this.readyState) {
            debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
            this.emitReserved("packet", packet);
            // Socket is live - any packet counts
            this.emitReserved("heartbeat");
            switch (packet.type) {
                case "open":
                    this.onHandshake(JSON.parse(packet.data));
                    break;
                case "ping":
                    this._sendPacket("pong");
                    this.emitReserved("ping");
                    this.emitReserved("pong");
                    this._resetPingTimeout();
                    break;
                case "error":
                    const err = new Error("server error");
                    // @ts-ignore
                    err.code = packet.data;
                    this._onError(err);
                    break;
                case "message":
                    this.emitReserved("data", packet.data);
                    this.emitReserved("message", packet.data);
                    break;
            }
        }
        else {
            debug('packet received with socket readyState "%s"', this.readyState);
        }
    }
    /**
     * Called upon handshake completion.
     *
     * @param {Object} data - handshake obj
     * @private
     */
    onHandshake(data) {
        this.emitReserved("handshake", data);
        this.id = data.sid;
        this.transport.query.sid = data.sid;
        this._pingInterval = data.pingInterval;
        this._pingTimeout = data.pingTimeout;
        this._maxPayload = data.maxPayload;
        this.onOpen();
        // In case open handler closes socket
        if ("closed" === this.readyState)
            return;
        this._resetPingTimeout();
    }
    /**
     * Sets and resets ping timeout timer based on server pings.
     *
     * @private
     */
    _resetPingTimeout() {
        this.clearTimeoutFn(this._pingTimeoutTimer);
        const delay = this._pingInterval + this._pingTimeout;
        this._pingTimeoutTime = Date.now() + delay;
        this._pingTimeoutTimer = this.setTimeoutFn(() => {
            this._onClose("ping timeout");
        }, delay);
        if (this.opts.autoUnref) {
            this._pingTimeoutTimer.unref();
        }
    }
    /**
     * Called on `drain` event
     *
     * @private
     */
    _onDrain() {
        this.writeBuffer.splice(0, this._prevBufferLen);
        // setting prevBufferLen = 0 is very important
        // for example, when upgrading, upgrade packet is sent over,
        // and a nonzero prevBufferLen could cause problems on `drain`
        this._prevBufferLen = 0;
        if (0 === this.writeBuffer.length) {
            this.emitReserved("drain");
        }
        else {
            this.flush();
        }
    }
    /**
     * Flush write buffers.
     *
     * @private
     */
    flush() {
        if ("closed" !== this.readyState &&
            this.transport.writable &&
            !this.upgrading &&
            this.writeBuffer.length) {
            const packets = this._getWritablePackets();
            debug("flushing %d packets in socket", packets.length);
            this.transport.send(packets);
            // keep track of current length of writeBuffer
            // splice writeBuffer and callbackBuffer on `drain`
            this._prevBufferLen = packets.length;
            this.emitReserved("flush");
        }
    }
    /**
     * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
     * long-polling)
     *
     * @private
     */
    _getWritablePackets() {
        const shouldCheckPayloadSize = this._maxPayload &&
            this.transport.name === "polling" &&
            this.writeBuffer.length > 1;
        if (!shouldCheckPayloadSize) {
            return this.writeBuffer;
        }
        let payloadSize = 1; // first packet type
        for (let i = 0; i < this.writeBuffer.length; i++) {
            const data = this.writeBuffer[i].data;
            if (data) {
                payloadSize += (0, util_js_1.byteLength)(data);
            }
            if (i > 0 && payloadSize > this._maxPayload) {
                debug("only send %d out of %d packets", i, this.writeBuffer.length);
                return this.writeBuffer.slice(0, i);
            }
            payloadSize += 2; // separator + packet type
        }
        debug("payload size is %d (max: %d)", payloadSize, this._maxPayload);
        return this.writeBuffer;
    }
    /**
     * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
     *
     * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
     * `write()` method then the message would not be buffered by the Socket.IO client.
     *
     * @return {boolean}
     * @private
     */
    /* private */ _hasPingExpired() {
        if (!this._pingTimeoutTime)
            return true;
        const hasExpired = Date.now() > this._pingTimeoutTime;
        if (hasExpired) {
            debug("throttled timer detected, scheduling connection close");
            this._pingTimeoutTime = 0;
            (0, globals_node_js_1.nextTick)(() => {
                this._onClose("ping timeout");
            }, this.setTimeoutFn);
        }
        return hasExpired;
    }
    /**
     * Sends a message.
     *
     * @param {String} msg - message.
     * @param {Object} options.
     * @param {Function} fn - callback function.
     * @return {Socket} for chaining.
     */
    write(msg, options, fn) {
        this._sendPacket("message", msg, options, fn);
        return this;
    }
    /**
     * Sends a message. Alias of {@link Socket#write}.
     *
     * @param {String} msg - message.
     * @param {Object} options.
     * @param {Function} fn - callback function.
     * @return {Socket} for chaining.
     */
    send(msg, options, fn) {
        this._sendPacket("message", msg, options, fn);
        return this;
    }
    /**
     * Sends a packet.
     *
     * @param {String} type: packet type.
     * @param {String} data.
     * @param {Object} options.
     * @param {Function} fn - callback function.
     * @private
     */
    _sendPacket(type, data, options, fn) {
        if ("function" === typeof data) {
            fn = data;
            data = undefined;
        }
        if ("function" === typeof options) {
            fn = options;
            options = null;
        }
        if ("closing" === this.readyState || "closed" === this.readyState) {
            return;
        }
        options = options || {};
        options.compress = false !== options.compress;
        const packet = {
            type: type,
            data: data,
            options: options,
        };
        this.emitReserved("packetCreate", packet);
        this.writeBuffer.push(packet);
        if (fn)
            this.once("flush", fn);
        this.flush();
    }
    /**
     * Closes the connection.
     */
    close() {
        const close = () => {
            this._onClose("forced close");
            debug("socket closing - telling transport to close");
            this.transport.close();
        };
        const cleanupAndClose = () => {
            this.off("upgrade", cleanupAndClose);
            this.off("upgradeError", cleanupAndClose);
            close();
        };
        const waitForUpgrade = () => {
            // wait for upgrade to finish since we can't send packets while pausing a transport
            this.once("upgrade", cleanupAndClose);
            this.once("upgradeError", cleanupAndClose);
        };
        if ("opening" === this.readyState || "open" === this.readyState) {
            this.readyState = "closing";
            if (this.writeBuffer.length) {
                this.once("drain", () => {
                    if (this.upgrading) {
                        waitForUpgrade();
                    }
                    else {
                        close();
                    }
                });
            }
            else if (this.upgrading) {
                waitForUpgrade();
            }
            else {
                close();
            }
        }
        return this;
    }
    /**
     * Called upon transport error
     *
     * @private
     */
    _onError(err) {
        debug("socket error %j", err);
        SocketWithoutUpgrade.priorWebsocketSuccess = false;
        if (this.opts.tryAllTransports &&
            this.transports.length > 1 &&
            this.readyState === "opening") {
            debug("trying next transport");
            this.transports.shift();
            return this._open();
        }
        this.emitReserved("error", err);
        this._onClose("transport error", err);
    }
    /**
     * Called upon transport close.
     *
     * @private
     */
    _onClose(reason, description) {
        if ("opening" === this.readyState ||
            "open" === this.readyState ||
            "closing" === this.readyState) {
            debug('socket close with reason: "%s"', reason);
            // clear timers
            this.clearTimeoutFn(this._pingTimeoutTimer);
            // stop event from firing again for transport
            this.transport.removeAllListeners("close");
            // ensure transport won't stay open
            this.transport.close();
            // ignore further transport communication
            this.transport.removeAllListeners();
            if (withEventListeners) {
                if (this._beforeunloadEventListener) {
                    removeEventListener("beforeunload", this._beforeunloadEventListener, false);
                }
                if (this._offlineEventListener) {
                    const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
                    if (i !== -1) {
                        debug("removing listener for the 'offline' event");
                        OFFLINE_EVENT_LISTENERS.splice(i, 1);
                    }
                }
            }
            // set ready state
            this.readyState = "closed";
            // clear session id
            this.id = null;
            // emit close event
            this.emitReserved("close", reason, description);
            // clean buffers after, so users can still
            // grab the buffers on `close` event
            this.writeBuffer = [];
            this._prevBufferLen = 0;
        }
    }
}
exports.SocketWithoutUpgrade = SocketWithoutUpgrade;
SocketWithoutUpgrade.protocol = engine_io_parser_1.protocol;
/**
 * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
 * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
 *
 * This class comes with an upgrade mechanism, which means that once the connection is established with the first
 * low-level transport, it will try to upgrade to a better transport.
 *
 * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
 *
 * @example
 * import { SocketWithUpgrade, WebSocket } from "engine.io-client";
 *
 * const socket = new SocketWithUpgrade({
 *   transports: [WebSocket]
 * });
 *
 * socket.on("open", () => {
 *   socket.send("hello");
 * });
 *
 * @see SocketWithoutUpgrade
 * @see Socket
 */
class SocketWithUpgrade extends SocketWithoutUpgrade {
    constructor() {
        super(...arguments);
        this._upgrades = [];
    }
    onOpen() {
        super.onOpen();
        if ("open" === this.readyState && this.opts.upgrade) {
            debug("starting upgrade probes");
            for (let i = 0; i < this._upgrades.length; i++) {
                this._probe(this._upgrades[i]);
            }
        }
    }
    /**
     * Probes a transport.
     *
     * @param {String} name - transport name
     * @private
     */
    _probe(name) {
        debug('probing transport "%s"', name);
        let transport = this.createTransport(name);
        let failed = false;
        SocketWithoutUpgrade.priorWebsocketSuccess = false;
        const onTransportOpen = () => {
            if (failed)
                return;
            debug('probe transport "%s" opened', name);
            transport.send([{ type: "ping", data: "probe" }]);
            transport.once("packet", (msg) => {
                if (failed)
                    return;
                if ("pong" === msg.type && "probe" === msg.data) {
                    debug('probe transport "%s" pong', name);
                    this.upgrading = true;
                    this.emitReserved("upgrading", transport);
                    if (!transport)
                        return;
                    SocketWithoutUpgrade.priorWebsocketSuccess =
                        "websocket" === transport.name;
                    debug('pausing current transport "%s"', this.transport.name);
                    this.transport.pause(() => {
                        if (failed)
                            return;
                        if ("closed" === this.readyState)
                            return;
                        debug("changing transport and sending upgrade packet");
                        cleanup();
                        this.setTransport(transport);
                        transport.send([{ type: "upgrade" }]);
                        this.emitReserved("upgrade", transport);
                        transport = null;
                        this.upgrading = false;
                        this.flush();
                    });
                }
                else {
                    debug('probe transport "%s" failed', name);
                    const err = new Error("probe error");
                    // @ts-ignore
                    err.transport = transport.name;
                    this.emitReserved("upgradeError", err);
                }
            });
        };
        function freezeTransport() {
            if (failed)
                return;
            // Any callback called by transport should be ignored since now
            failed = true;
            cleanup();
            transport.close();
            transport = null;
        }
        // Handle any error that happens while probing
        const onerror = (err) => {
            const error = new Error("probe error: " + err);
            // @ts-ignore
            error.transport = transport.name;
            freezeTransport();
            debug('probe transport "%s" failed because of error: %s', name, err);
            this.emitReserved("upgradeError", error);
        };
        function onTransportClose() {
            onerror("transport closed");
        }
        // When the socket is closed while we're probing
        function onclose() {
            onerror("socket closed");
        }
        // When the socket is upgraded while we're probing
        function onupgrade(to) {
            if (transport && to.name !== transport.name) {
                debug('"%s" works - aborting "%s"', to.name, transport.name);
                freezeTransport();
            }
        }
        // Remove all listeners on the transport and on self
        const cleanup = () => {
            transport.removeListener("open", onTransportOpen);
            transport.removeListener("error", onerror);
            transport.removeListener("close", onTransportClose);
            this.off("close", onclose);
            this.off("upgrading", onupgrade);
        };
        transport.once("open", onTransportOpen);
        transport.once("error", onerror);
        transport.once("close", onTransportClose);
        this.once("close", onclose);
        this.once("upgrading", onupgrade);
        if (this._upgrades.indexOf("webtransport") !== -1 &&
            name !== "webtransport") {
            // favor WebTransport
            this.setTimeoutFn(() => {
                if (!failed) {
                    transport.open();
                }
            }, 200);
        }
        else {
            transport.open();
        }
    }
    onHandshake(data) {
        this._upgrades = this._filterUpgrades(data.upgrades);
        super.onHandshake(data);
    }
    /**
     * Filters upgrades, returning only those matching client transports.
     *
     * @param {Array} upgrades - server upgrades
     * @private
     */
    _filterUpgrades(upgrades) {
        const filteredUpgrades = [];
        for (let i = 0; i < upgrades.length; i++) {
            if (~this.transports.indexOf(upgrades[i]))
                filteredUpgrades.push(upgrades[i]);
        }
        return filteredUpgrades;
    }
}
exports.SocketWithUpgrade = SocketWithUpgrade;
/**
 * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
 * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
 *
 * This class comes with an upgrade mechanism, which means that once the connection is established with the first
 * low-level transport, it will try to upgrade to a better transport.
 *
 * @example
 * import { Socket } from "engine.io-client";
 *
 * const socket = new Socket();
 *
 * socket.on("open", () => {
 *   socket.send("hello");
 * });
 *
 * @see SocketWithoutUpgrade
 * @see SocketWithUpgrade
 */
class Socket extends SocketWithUpgrade {
    constructor(uri, opts = {}) {
        const o = typeof uri === "object" ? uri : opts;
        if (!o.transports ||
            (o.transports && typeof o.transports[0] === "string")) {
            o.transports = (o.transports || ["polling", "websocket", "webtransport"])
                .map((transportName) => index_js_1.transports[transportName])
                .filter((t) => !!t);
        }
        super(uri, o);
    }
}
exports.Socket = Socket;
 
},{"./contrib/parseqs.js":8,"./contrib/parseuri.js":9,"./globals.node.js":10,"./transports/index.js":14,"./util.js":20,"@socket.io/component-emitter":6,"debug":21,"engine.io-parser":27}],13:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Transport = exports.TransportError = void 0;
const engine_io_parser_1 = require("engine.io-parser");
const component_emitter_1 = require("@socket.io/component-emitter");
const util_js_1 = require("./util.js");
const parseqs_js_1 = require("./contrib/parseqs.js");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("engine.io-client:transport"); // debug()
class TransportError extends Error {
    constructor(reason, description, context) {
        super(reason);
        this.description = description;
        this.context = context;
        this.type = "TransportError";
    }
}
exports.TransportError = TransportError;
class Transport extends component_emitter_1.Emitter {
    /**
     * Transport abstract constructor.
     *
     * @param {Object} opts - options
     * @protected
     */
    constructor(opts) {
        super();
        this.writable = false;
        (0, util_js_1.installTimerFunctions)(this, opts);
        this.opts = opts;
        this.query = opts.query;
        this.socket = opts.socket;
        this.supportsBinary = !opts.forceBase64;
    }
    /**
     * Emits an error.
     *
     * @param {String} reason
     * @param description
     * @param context - the error context
     * @return {Transport} for chaining
     * @protected
     */
    onError(reason, description, context) {
        super.emitReserved("error", new TransportError(reason, description, context));
        return this;
    }
    /**
     * Opens the transport.
     */
    open() {
        this.readyState = "opening";
        this.doOpen();
        return this;
    }
    /**
     * Closes the transport.
     */
    close() {
        if (this.readyState === "opening" || this.readyState === "open") {
            this.doClose();
            this.onClose();
        }
        return this;
    }
    /**
     * Sends multiple packets.
     *
     * @param {Array} packets
     */
    send(packets) {
        if (this.readyState === "open") {
            this.write(packets);
        }
        else {
            // this might happen if the transport was silently closed in the beforeunload event handler
            debug("transport is not open, discarding packets");
        }
    }
    /**
     * Called upon open
     *
     * @protected
     */
    onOpen() {
        this.readyState = "open";
        this.writable = true;
        super.emitReserved("open");
    }
    /**
     * Called with data.
     *
     * @param {String} data
     * @protected
     */
    onData(data) {
        const packet = (0, engine_io_parser_1.decodePacket)(data, this.socket.binaryType);
        this.onPacket(packet);
    }
    /**
     * Called with a decoded packet.
     *
     * @protected
     */
    onPacket(packet) {
        super.emitReserved("packet", packet);
    }
    /**
     * Called upon close.
     *
     * @protected
     */
    onClose(details) {
        this.readyState = "closed";
        super.emitReserved("close", details);
    }
    /**
     * Pauses the transport, in order not to lose packets during an upgrade.
     *
     * @param onPause
     */
    pause(onPause) { }
    createUri(schema, query = {}) {
        return (schema +
            "://" +
            this._hostname() +
            this._port() +
            this.opts.path +
            this._query(query));
    }
    _hostname() {
        const hostname = this.opts.hostname;
        return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
    }
    _port() {
        if (this.opts.port &&
            ((this.opts.secure && Number(this.opts.port !== 443)) ||
                (!this.opts.secure && Number(this.opts.port) !== 80))) {
            return ":" + this.opts.port;
        }
        else {
            return "";
        }
    }
    _query(query) {
        const encodedQuery = (0, parseqs_js_1.encode)(query);
        return encodedQuery.length ? "?" + encodedQuery : "";
    }
}
exports.Transport = Transport;
 
},{"./contrib/parseqs.js":8,"./util.js":20,"@socket.io/component-emitter":6,"debug":21,"engine.io-parser":27}],14:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transports = void 0;
const polling_xhr_node_js_1 = require("./polling-xhr.node.js");
const websocket_node_js_1 = require("./websocket.node.js");
const webtransport_js_1 = require("./webtransport.js");
exports.transports = {
    websocket: websocket_node_js_1.WS,
    webtransport: webtransport_js_1.WT,
    polling: polling_xhr_node_js_1.XHR,
};
 
},{"./polling-xhr.node.js":16,"./websocket.node.js":18,"./webtransport.js":19}],15:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Fetch = void 0;
const polling_js_1 = require("./polling.js");
/**
 * HTTP long-polling based on the built-in `fetch()` method.
 *
 * Usage: browser, Node.js (since v18), Deno, Bun
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/fetch
 * @see https://caniuse.com/fetch
 * @see https://nodejs.org/api/globals.html#fetch
 */
class Fetch extends polling_js_1.Polling {
    doPoll() {
        this._fetch()
            .then((res) => {
            if (!res.ok) {
                return this.onError("fetch read error", res.status, res);
            }
            res.text().then((data) => this.onData(data));
        })
            .catch((err) => {
            this.onError("fetch read error", err);
        });
    }
    doWrite(data, callback) {
        this._fetch(data)
            .then((res) => {
            if (!res.ok) {
                return this.onError("fetch write error", res.status, res);
            }
            callback();
        })
            .catch((err) => {
            this.onError("fetch write error", err);
        });
    }
    _fetch(data) {
        var _a;
        const isPost = data !== undefined;
        const headers = new Headers(this.opts.extraHeaders);
        if (isPost) {
            headers.set("content-type", "text/plain;charset=UTF-8");
        }
        (_a = this.socket._cookieJar) === null || _a === void 0 ? void 0 : _a.appendCookies(headers);
        return fetch(this.uri(), {
            method: isPost ? "POST" : "GET",
            body: isPost ? data : null,
            headers,
            credentials: this.opts.withCredentials ? "include" : "omit",
        }).then((res) => {
            var _a;
            // @ts-ignore getSetCookie() was added in Node.js v19.7.0
            (_a = this.socket._cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(res.headers.getSetCookie());
            return res;
        });
    }
}
exports.Fetch = Fetch;
 
},{"./polling.js":17}],16:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.XHR = exports.Request = exports.BaseXHR = void 0;
const polling_js_1 = require("./polling.js");
const component_emitter_1 = require("@socket.io/component-emitter");
const util_js_1 = require("../util.js");
const globals_node_js_1 = require("../globals.node.js");
const has_cors_js_1 = require("../contrib/has-cors.js");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("engine.io-client:polling"); // debug()
function empty() { }
class BaseXHR extends polling_js_1.Polling {
    /**
     * XHR Polling constructor.
     *
     * @param {Object} opts
     * @package
     */
    constructor(opts) {
        super(opts);
        if (typeof location !== "undefined") {
            const isSSL = "https:" === location.protocol;
            let port = location.port;
            // some user agents have empty `location.port`
            if (!port) {
                port = isSSL ? "443" : "80";
            }
            this.xd =
                (typeof location !== "undefined" &&
                    opts.hostname !== location.hostname) ||
                    port !== opts.port;
        }
    }
    /**
     * Sends data.
     *
     * @param {String} data to send.
     * @param {Function} called upon flush.
     * @private
     */
    doWrite(data, fn) {
        const req = this.request({
            method: "POST",
            data: data,
        });
        req.on("success", fn);
        req.on("error", (xhrStatus, context) => {
            this.onError("xhr post error", xhrStatus, context);
        });
    }
    /**
     * Starts a poll cycle.
     *
     * @private
     */
    doPoll() {
        debug("xhr poll");
        const req = this.request();
        req.on("data", this.onData.bind(this));
        req.on("error", (xhrStatus, context) => {
            this.onError("xhr poll error", xhrStatus, context);
        });
        this.pollXhr = req;
    }
}
exports.BaseXHR = BaseXHR;
class Request extends component_emitter_1.Emitter {
    /**
     * Request constructor
     *
     * @param {Object} options
     * @package
     */
    constructor(createRequest, uri, opts) {
        super();
        this.createRequest = createRequest;
        (0, util_js_1.installTimerFunctions)(this, opts);
        this._opts = opts;
        this._method = opts.method || "GET";
        this._uri = uri;
        this._data = undefined !== opts.data ? opts.data : null;
        this._create();
    }
    /**
     * Creates the XHR object and sends the request.
     *
     * @private
     */
    _create() {
        var _a;
        const opts = (0, util_js_1.pick)(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
        opts.xdomain = !!this._opts.xd;
        const xhr = (this._xhr = this.createRequest(opts));
        try {
            debug("xhr open %s: %s", this._method, this._uri);
            xhr.open(this._method, this._uri, true);
            try {
                if (this._opts.extraHeaders) {
                    // @ts-ignore
                    xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
                    for (let i in this._opts.extraHeaders) {
                        if (this._opts.extraHeaders.hasOwnProperty(i)) {
                            xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
                        }
                    }
                }
            }
            catch (e) { }
            if ("POST" === this._method) {
                try {
                    xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
                }
                catch (e) { }
            }
            try {
                xhr.setRequestHeader("Accept", "*/*");
            }
            catch (e) { }
            (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
            // ie6 check
            if ("withCredentials" in xhr) {
                xhr.withCredentials = this._opts.withCredentials;
            }
            if (this._opts.requestTimeout) {
                xhr.timeout = this._opts.requestTimeout;
            }
            xhr.onreadystatechange = () => {
                var _a;
                if (xhr.readyState === 3) {
                    (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(
                    // @ts-ignore
                    xhr.getResponseHeader("set-cookie"));
                }
                if (4 !== xhr.readyState)
                    return;
                if (200 === xhr.status || 1223 === xhr.status) {
                    this._onLoad();
                }
                else {
                    // make sure the `error` event handler that's user-set
                    // does not throw in the same tick and gets caught here
                    this.setTimeoutFn(() => {
                        this._onError(typeof xhr.status === "number" ? xhr.status : 0);
                    }, 0);
                }
            };
            debug("xhr data %s", this._data);
            xhr.send(this._data);
        }
        catch (e) {
            // Need to defer since .create() is called directly from the constructor
            // and thus the 'error' event can only be only bound *after* this exception
            // occurs.  Therefore, also, we cannot throw here at all.
            this.setTimeoutFn(() => {
                this._onError(e);
            }, 0);
            return;
        }
        if (typeof document !== "undefined") {
            this._index = Request.requestsCount++;
            Request.requests[this._index] = this;
        }
    }
    /**
     * Called upon error.
     *
     * @private
     */
    _onError(err) {
        this.emitReserved("error", err, this._xhr);
        this._cleanup(true);
    }
    /**
     * Cleans up house.
     *
     * @private
     */
    _cleanup(fromError) {
        if ("undefined" === typeof this._xhr || null === this._xhr) {
            return;
        }
        this._xhr.onreadystatechange = empty;
        if (fromError) {
            try {
                this._xhr.abort();
            }
            catch (e) { }
        }
        if (typeof document !== "undefined") {
            delete Request.requests[this._index];
        }
        this._xhr = null;
    }
    /**
     * Called upon load.
     *
     * @private
     */
    _onLoad() {
        const data = this._xhr.responseText;
        if (data !== null) {
            this.emitReserved("data", data);
            this.emitReserved("success");
            this._cleanup();
        }
    }
    /**
     * Aborts the request.
     *
     * @package
     */
    abort() {
        this._cleanup();
    }
}
exports.Request = Request;
Request.requestsCount = 0;
Request.requests = {};
/**
 * Aborts pending requests when unloading the window. This is needed to prevent
 * memory leaks (e.g. when using IE) and to ensure that no spurious error is
 * emitted.
 */
if (typeof document !== "undefined") {
    // @ts-ignore
    if (typeof attachEvent === "function") {
        // @ts-ignore
        attachEvent("onunload", unloadHandler);
    }
    else if (typeof addEventListener === "function") {
        const terminationEvent = "onpagehide" in globals_node_js_1.globalThisShim ? "pagehide" : "unload";
        addEventListener(terminationEvent, unloadHandler, false);
    }
}
function unloadHandler() {
    for (let i in Request.requests) {
        if (Request.requests.hasOwnProperty(i)) {
            Request.requests[i].abort();
        }
    }
}
const hasXHR2 = (function () {
    const xhr = newRequest({
        xdomain: false,
    });
    return xhr && xhr.responseType !== null;
})();
/**
 * HTTP long-polling based on the built-in `XMLHttpRequest` object.
 *
 * Usage: browser
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
 */
class XHR extends BaseXHR {
    constructor(opts) {
        super(opts);
        const forceBase64 = opts && opts.forceBase64;
        this.supportsBinary = hasXHR2 && !forceBase64;
    }
    request(opts = {}) {
        Object.assign(opts, { xd: this.xd }, this.opts);
        return new Request(newRequest, this.uri(), opts);
    }
}
exports.XHR = XHR;
function newRequest(opts) {
    const xdomain = opts.xdomain;
    // XMLHttpRequest can be disabled on IE
    try {
        if ("undefined" !== typeof XMLHttpRequest && (!xdomain || has_cors_js_1.hasCORS)) {
            return new XMLHttpRequest();
        }
    }
    catch (e) { }
    if (!xdomain) {
        try {
            return new globals_node_js_1.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
        }
        catch (e) { }
    }
}
 
},{"../contrib/has-cors.js":7,"../globals.node.js":10,"../util.js":20,"./polling.js":17,"@socket.io/component-emitter":6,"debug":21}],17:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Polling = void 0;
const transport_js_1 = require("../transport.js");
const util_js_1 = require("../util.js");
const engine_io_parser_1 = require("engine.io-parser");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("engine.io-client:polling"); // debug()
class Polling extends transport_js_1.Transport {
    constructor() {
        super(...arguments);
        this._polling = false;
    }
    get name() {
        return "polling";
    }
    /**
     * Opens the socket (triggers polling). We write a PING message to determine
     * when the transport is open.
     *
     * @protected
     */
    doOpen() {
        this._poll();
    }
    /**
     * Pauses polling.
     *
     * @param {Function} onPause - callback upon buffers are flushed and transport is paused
     * @package
     */
    pause(onPause) {
        this.readyState = "pausing";
        const pause = () => {
            debug("paused");
            this.readyState = "paused";
            onPause();
        };
        if (this._polling || !this.writable) {
            let total = 0;
            if (this._polling) {
                debug("we are currently polling - waiting to pause");
                total++;
                this.once("pollComplete", function () {
                    debug("pre-pause polling complete");
                    --total || pause();
                });
            }
            if (!this.writable) {
                debug("we are currently writing - waiting to pause");
                total++;
                this.once("drain", function () {
                    debug("pre-pause writing complete");
                    --total || pause();
                });
            }
        }
        else {
            pause();
        }
    }
    /**
     * Starts polling cycle.
     *
     * @private
     */
    _poll() {
        debug("polling");
        this._polling = true;
        this.doPoll();
        this.emitReserved("poll");
    }
    /**
     * Overloads onData to detect payloads.
     *
     * @protected
     */
    onData(data) {
        debug("polling got data %s", data);
        const callback = (packet) => {
            // if its the first message we consider the transport open
            if ("opening" === this.readyState && packet.type === "open") {
                this.onOpen();
            }
            // if its a close packet, we close the ongoing requests
            if ("close" === packet.type) {
                this.onClose({ description: "transport closed by the server" });
                return false;
            }
            // otherwise bypass onData and handle the message
            this.onPacket(packet);
        };
        // decode payload
        (0, engine_io_parser_1.decodePayload)(data, this.socket.binaryType).forEach(callback);
        // if an event did not trigger closing
        if ("closed" !== this.readyState) {
            // if we got data we're not polling
            this._polling = false;
            this.emitReserved("pollComplete");
            if ("open" === this.readyState) {
                this._poll();
            }
            else {
                debug('ignoring poll - transport state "%s"', this.readyState);
            }
        }
    }
    /**
     * For polling, send a close packet.
     *
     * @protected
     */
    doClose() {
        const close = () => {
            debug("writing close packet");
            this.write([{ type: "close" }]);
        };
        if ("open" === this.readyState) {
            debug("transport open - closing");
            close();
        }
        else {
            // in case we're trying to close while
            // handshaking is in progress (GH-164)
            debug("transport not open - deferring close");
            this.once("open", close);
        }
    }
    /**
     * Writes a packets payload.
     *
     * @param {Array} packets - data packets
     * @protected
     */
    write(packets) {
        this.writable = false;
        (0, engine_io_parser_1.encodePayload)(packets, (data) => {
            this.doWrite(data, () => {
                this.writable = true;
                this.emitReserved("drain");
            });
        });
    }
    /**
     * Generates uri for connection.
     *
     * @private
     */
    uri() {
        const schema = this.opts.secure ? "https" : "http";
        const query = this.query || {};
        // cache busting is forced
        if (false !== this.opts.timestampRequests) {
            query[this.opts.timestampParam] = (0, util_js_1.randomString)();
        }
        if (!this.supportsBinary && !query.sid) {
            query.b64 = 1;
        }
        return this.createUri(schema, query);
    }
}
exports.Polling = Polling;
 
},{"../transport.js":13,"../util.js":20,"debug":21,"engine.io-parser":27}],18:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WS = exports.BaseWS = void 0;
const transport_js_1 = require("../transport.js");
const util_js_1 = require("../util.js");
const engine_io_parser_1 = require("engine.io-parser");
const globals_node_js_1 = require("../globals.node.js");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("engine.io-client:websocket"); // debug()
// detect ReactNative environment
const isReactNative = typeof navigator !== "undefined" &&
    typeof navigator.product === "string" &&
    navigator.product.toLowerCase() === "reactnative";
class BaseWS extends transport_js_1.Transport {
    get name() {
        return "websocket";
    }
    doOpen() {
        const uri = this.uri();
        const protocols = this.opts.protocols;
        // React Native only supports the 'headers' option, and will print a warning if anything else is passed
        const opts = isReactNative
            ? {}
            : (0, util_js_1.pick)(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
        if (this.opts.extraHeaders) {
            opts.headers = this.opts.extraHeaders;
        }
        try {
            this.ws = this.createSocket(uri, protocols, opts);
        }
        catch (err) {
            return this.emitReserved("error", err);
        }
        this.ws.binaryType = this.socket.binaryType;
        this.addEventListeners();
    }
    /**
     * Adds event listeners to the socket
     *
     * @private
     */
    addEventListeners() {
        this.ws.onopen = () => {
            if (this.opts.autoUnref) {
                this.ws._socket.unref();
            }
            this.onOpen();
        };
        this.ws.onclose = (closeEvent) => this.onClose({
            description: "websocket connection closed",
            context: closeEvent,
        });
        this.ws.onmessage = (ev) => this.onData(ev.data);
        this.ws.onerror = (e) => this.onError("websocket error", e);
    }
    write(packets) {
        this.writable = false;
        // encodePacket efficient as it uses WS framing
        // no need for encodePayload
        for (let i = 0; i < packets.length; i++) {
            const packet = packets[i];
            const lastPacket = i === packets.length - 1;
            (0, engine_io_parser_1.encodePacket)(packet, this.supportsBinary, (data) => {
                // Sometimes the websocket has already been closed but the browser didn't
                // have a chance of informing us about it yet, in that case send will
                // throw an error
                try {
                    this.doWrite(packet, data);
                }
                catch (e) {
                    debug("websocket closed before onclose event");
                }
                if (lastPacket) {
                    // fake drain
                    // defer to next tick to allow Socket to clear writeBuffer
                    (0, globals_node_js_1.nextTick)(() => {
                        this.writable = true;
                        this.emitReserved("drain");
                    }, this.setTimeoutFn);
                }
            });
        }
    }
    doClose() {
        if (typeof this.ws !== "undefined") {
            this.ws.onerror = () => { };
            this.ws.close();
            this.ws = null;
        }
    }
    /**
     * Generates uri for connection.
     *
     * @private
     */
    uri() {
        const schema = this.opts.secure ? "wss" : "ws";
        const query = this.query || {};
        // append timestamp to URI
        if (this.opts.timestampRequests) {
            query[this.opts.timestampParam] = (0, util_js_1.randomString)();
        }
        // communicate binary support capabilities
        if (!this.supportsBinary) {
            query.b64 = 1;
        }
        return this.createUri(schema, query);
    }
}
exports.BaseWS = BaseWS;
const WebSocketCtor = globals_node_js_1.globalThisShim.WebSocket || globals_node_js_1.globalThisShim.MozWebSocket;
/**
 * WebSocket transport based on the built-in `WebSocket` object.
 *
 * Usage: browser, Node.js (since v21), Deno, Bun
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
 * @see https://caniuse.com/mdn-api_websocket
 * @see https://nodejs.org/api/globals.html#websocket
 */
class WS extends BaseWS {
    createSocket(uri, protocols, opts) {
        return !isReactNative
            ? protocols
                ? new WebSocketCtor(uri, protocols)
                : new WebSocketCtor(uri)
            : new WebSocketCtor(uri, protocols, opts);
    }
    doWrite(_packet, data) {
        this.ws.send(data);
    }
}
exports.WS = WS;
 
},{"../globals.node.js":10,"../transport.js":13,"../util.js":20,"debug":21,"engine.io-parser":27}],19:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WT = void 0;
const transport_js_1 = require("../transport.js");
const globals_node_js_1 = require("../globals.node.js");
const engine_io_parser_1 = require("engine.io-parser");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("engine.io-client:webtransport"); // debug()
/**
 * WebTransport transport based on the built-in `WebTransport` object.
 *
 * Usage: browser, Node.js (with the `@fails-components/webtransport` package)
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
 * @see https://caniuse.com/webtransport
 */
class WT extends transport_js_1.Transport {
    get name() {
        return "webtransport";
    }
    doOpen() {
        try {
            // @ts-ignore
            this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
        }
        catch (err) {
            return this.emitReserved("error", err);
        }
        this._transport.closed
            .then(() => {
            debug("transport closed gracefully");
            this.onClose();
        })
            .catch((err) => {
            debug("transport closed due to %s", err);
            this.onError("webtransport error", err);
        });
        // note: we could have used async/await, but that would require some additional polyfills
        this._transport.ready.then(() => {
            this._transport.createBidirectionalStream().then((stream) => {
                const decoderStream = (0, engine_io_parser_1.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
                const reader = stream.readable.pipeThrough(decoderStream).getReader();
                const encoderStream = (0, engine_io_parser_1.createPacketEncoderStream)();
                encoderStream.readable.pipeTo(stream.writable);
                this._writer = encoderStream.writable.getWriter();
                const read = () => {
                    reader
                        .read()
                        .then(({ done, value }) => {
                        if (done) {
                            debug("session is closed");
                            return;
                        }
                        debug("received chunk: %o", value);
                        this.onPacket(value);
                        read();
                    })
                        .catch((err) => {
                        debug("an error occurred while reading: %s", err);
                    });
                };
                read();
                const packet = { type: "open" };
                if (this.query.sid) {
                    packet.data = `{"sid":"${this.query.sid}"}`;
                }
                this._writer.write(packet).then(() => this.onOpen());
            });
        });
    }
    write(packets) {
        this.writable = false;
        for (let i = 0; i < packets.length; i++) {
            const packet = packets[i];
            const lastPacket = i === packets.length - 1;
            this._writer.write(packet).then(() => {
                if (lastPacket) {
                    (0, globals_node_js_1.nextTick)(() => {
                        this.writable = true;
                        this.emitReserved("drain");
                    }, this.setTimeoutFn);
                }
            });
        }
    }
    doClose() {
        var _a;
        (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
    }
}
exports.WT = WT;
 
},{"../globals.node.js":10,"../transport.js":13,"debug":21,"engine.io-parser":27}],20:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pick = pick;
exports.installTimerFunctions = installTimerFunctions;
exports.byteLength = byteLength;
exports.randomString = randomString;
const globals_node_js_1 = require("./globals.node.js");
function pick(obj, ...attr) {
    return attr.reduce((acc, k) => {
        if (obj.hasOwnProperty(k)) {
            acc[k] = obj[k];
        }
        return acc;
    }, {});
}
// Keep a reference to the real timeout functions so they can be used when overridden
const NATIVE_SET_TIMEOUT = globals_node_js_1.globalThisShim.setTimeout;
const NATIVE_CLEAR_TIMEOUT = globals_node_js_1.globalThisShim.clearTimeout;
function installTimerFunctions(obj, opts) {
    if (opts.useNativeTimers) {
        obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globals_node_js_1.globalThisShim);
        obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globals_node_js_1.globalThisShim);
    }
    else {
        obj.setTimeoutFn = globals_node_js_1.globalThisShim.setTimeout.bind(globals_node_js_1.globalThisShim);
        obj.clearTimeoutFn = globals_node_js_1.globalThisShim.clearTimeout.bind(globals_node_js_1.globalThisShim);
    }
}
// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
const BASE64_OVERHEAD = 1.33;
// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
function byteLength(obj) {
    if (typeof obj === "string") {
        return utf8Length(obj);
    }
    // arraybuffer or blob
    return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
}
function utf8Length(str) {
    let c = 0, length = 0;
    for (let i = 0, l = str.length; i < l; i++) {
        c = str.charCodeAt(i);
        if (c < 0x80) {
            length += 1;
        }
        else if (c < 0x800) {
            length += 2;
        }
        else if (c < 0xd800 || c >= 0xe000) {
            length += 3;
        }
        else {
            i++;
            length += 4;
        }
    }
    return length;
}
/**
 * Generates a random 8-characters string.
 */
function randomString() {
    return (Date.now().toString(36).substring(3) +
        Math.random().toString(36).substring(2, 5));
}
 
},{"./globals.node.js":10}],21:[function(require,module,exports){
(function (process){(function (){
/* eslint-env browser */
 
/**
 * This is the web browser implementation of `debug()`.
 */
 
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
	let warned = false;
 
	return () => {
		if (!warned) {
			warned = true;
			console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
		}
	};
})();
 
/**
 * Colors.
 */
 
exports.colors = [
	'#0000CC',
	'#0000FF',
	'#0033CC',
	'#0033FF',
	'#0066CC',
	'#0066FF',
	'#0099CC',
	'#0099FF',
	'#00CC00',
	'#00CC33',
	'#00CC66',
	'#00CC99',
	'#00CCCC',
	'#00CCFF',
	'#3300CC',
	'#3300FF',
	'#3333CC',
	'#3333FF',
	'#3366CC',
	'#3366FF',
	'#3399CC',
	'#3399FF',
	'#33CC00',
	'#33CC33',
	'#33CC66',
	'#33CC99',
	'#33CCCC',
	'#33CCFF',
	'#6600CC',
	'#6600FF',
	'#6633CC',
	'#6633FF',
	'#66CC00',
	'#66CC33',
	'#9900CC',
	'#9900FF',
	'#9933CC',
	'#9933FF',
	'#99CC00',
	'#99CC33',
	'#CC0000',
	'#CC0033',
	'#CC0066',
	'#CC0099',
	'#CC00CC',
	'#CC00FF',
	'#CC3300',
	'#CC3333',
	'#CC3366',
	'#CC3399',
	'#CC33CC',
	'#CC33FF',
	'#CC6600',
	'#CC6633',
	'#CC9900',
	'#CC9933',
	'#CCCC00',
	'#CCCC33',
	'#FF0000',
	'#FF0033',
	'#FF0066',
	'#FF0099',
	'#FF00CC',
	'#FF00FF',
	'#FF3300',
	'#FF3333',
	'#FF3366',
	'#FF3399',
	'#FF33CC',
	'#FF33FF',
	'#FF6600',
	'#FF6633',
	'#FF9900',
	'#FF9933',
	'#FFCC00',
	'#FFCC33'
];
 
/**
 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
 * and the Firebug extension (any Firefox version) are known
 * to support "%c" CSS customizations.
 *
 * TODO: add a `localStorage` variable to explicitly enable/disable colors
 */
 
// eslint-disable-next-line complexity
function useColors() {
	// NB: In an Electron preload script, document will be defined but not fully
	// initialized. Since we know we're in Chrome, we'll just detect this case
	// explicitly
	if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
		return true;
	}
 
	// Internet Explorer and Edge do not support colors.
	if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
		return false;
	}
 
	let m;
 
	// Is webkit? http://stackoverflow.com/a/16459606/376773
	// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
	return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
		// Is firebug? http://stackoverflow.com/a/398120/376773
		(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
		// Is firefox >= v31?
		// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
		(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
		// Double check webkit in userAgent just in case we are in a worker
		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
 
/**
 * Colorize log arguments if enabled.
 *
 * @api public
 */
 
function formatArgs(args) {
	args[0] = (this.useColors ? '%c' : '') +
		this.namespace +
		(this.useColors ? ' %c' : ' ') +
		args[0] +
		(this.useColors ? '%c ' : ' ') +
		'+' + module.exports.humanize(this.diff);
 
	if (!this.useColors) {
		return;
	}
 
	const c = 'color: ' + this.color;
	args.splice(1, 0, c, 'color: inherit');
 
	// The final "%c" is somewhat tricky, because there could be other
	// arguments passed either before or after the %c, so we need to
	// figure out the correct index to insert the CSS into
	let index = 0;
	let lastC = 0;
	args[0].replace(/%[a-zA-Z%]/g, match => {
		if (match === '%%') {
			return;
		}
		index++;
		if (match === '%c') {
			// We only are interested in the *last* %c
			// (the user may have provided their own)
			lastC = index;
		}
	});
 
	args.splice(lastC, 0, c);
}
 
/**
 * Invokes `console.debug()` when available.
 * No-op when `console.debug` is not a "function".
 * If `console.debug` is not available, falls back
 * to `console.log`.
 *
 * @api public
 */
exports.log = console.debug || console.log || (() => {});
 
/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */
function save(namespaces) {
	try {
		if (namespaces) {
			exports.storage.setItem('debug', namespaces);
		} else {
			exports.storage.removeItem('debug');
		}
	} catch (error) {
		// Swallow
		// XXX (@Qix-) should we be logging these?
	}
}
 
/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */
function load() {
	let r;
	try {
		r = exports.storage.getItem('debug');
	} catch (error) {
		// Swallow
		// XXX (@Qix-) should we be logging these?
	}
 
	// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
	if (!r && typeof process !== 'undefined' && 'env' in process) {
		r = process.env.DEBUG;
	}
 
	return r;
}
 
/**
 * Localstorage attempts to return the localstorage.
 *
 * This is necessary because safari throws
 * when a user disables cookies/localstorage
 * and you attempt to access it.
 *
 * @return {LocalStorage}
 * @api private
 */
 
function localstorage() {
	try {
		// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
		// The Browser also has localStorage in the global context.
		return localStorage;
	} catch (error) {
		// Swallow
		// XXX (@Qix-) should we be logging these?
	}
}
 
module.exports = require('./common')(exports);
 
const {formatters} = module.exports;
 
/**
 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
 */
 
formatters.j = function (v) {
	try {
		return JSON.stringify(v);
	} catch (error) {
		return '[UnexpectedJSONParseError]: ' + error.message;
	}
};
 
}).call(this)}).call(this,require('_process'))
},{"./common":22,"_process":29}],22:[function(require,module,exports){
 
/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 */
 
function setup(env) {
	createDebug.debug = createDebug;
	createDebug.default = createDebug;
	createDebug.coerce = coerce;
	createDebug.disable = disable;
	createDebug.enable = enable;
	createDebug.enabled = enabled;
	createDebug.humanize = require('ms');
	createDebug.destroy = destroy;
 
	Object.keys(env).forEach(key => {
		createDebug[key] = env[key];
	});
 
	/**
	* The currently active debug mode names, and names to skip.
	*/
 
	createDebug.names = [];
	createDebug.skips = [];
 
	/**
	* Map of special "%n" handling functions, for the debug "format" argument.
	*
	* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
	*/
	createDebug.formatters = {};
 
	/**
	* Selects a color for a debug namespace
	* @param {String} namespace The namespace string for the debug instance to be colored
	* @return {Number|String} An ANSI color code for the given namespace
	* @api private
	*/
	function selectColor(namespace) {
		let hash = 0;
 
		for (let i = 0; i < namespace.length; i++) {
			hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
			hash |= 0; // Convert to 32bit integer
		}
 
		return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
	}
	createDebug.selectColor = selectColor;
 
	/**
	* Create a debugger with the given `namespace`.
	*
	* @param {String} namespace
	* @return {Function}
	* @api public
	*/
	function createDebug(namespace) {
		let prevTime;
		let enableOverride = null;
		let namespacesCache;
		let enabledCache;
 
		function debug(...args) {
			// Disabled?
			if (!debug.enabled) {
				return;
			}
 
			const self = debug;
 
			// Set `diff` timestamp
			const curr = Number(new Date());
			const ms = curr - (prevTime || curr);
			self.diff = ms;
			self.prev = prevTime;
			self.curr = curr;
			prevTime = curr;
 
			args[0] = createDebug.coerce(args[0]);
 
			if (typeof args[0] !== 'string') {
				// Anything else let's inspect with %O
				args.unshift('%O');
			}
 
			// Apply any `formatters` transformations
			let index = 0;
			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
				// If we encounter an escaped % then don't increase the array index
				if (match === '%%') {
					return '%';
				}
				index++;
				const formatter = createDebug.formatters[format];
				if (typeof formatter === 'function') {
					const val = args[index];
					match = formatter.call(self, val);
 
					// Now we need to remove `args[index]` since it's inlined in the `format`
					args.splice(index, 1);
					index--;
				}
				return match;
			});
 
			// Apply env-specific formatting (colors, etc.)
			createDebug.formatArgs.call(self, args);
 
			const logFn = self.log || createDebug.log;
			logFn.apply(self, args);
		}
 
		debug.namespace = namespace;
		debug.useColors = createDebug.useColors();
		debug.color = createDebug.selectColor(namespace);
		debug.extend = extend;
		debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
 
		Object.defineProperty(debug, 'enabled', {
			enumerable: true,
			configurable: false,
			get: () => {
				if (enableOverride !== null) {
					return enableOverride;
				}
				if (namespacesCache !== createDebug.namespaces) {
					namespacesCache = createDebug.namespaces;
					enabledCache = createDebug.enabled(namespace);
				}
 
				return enabledCache;
			},
			set: v => {
				enableOverride = v;
			}
		});
 
		// Env-specific initialization logic for debug instances
		if (typeof createDebug.init === 'function') {
			createDebug.init(debug);
		}
 
		return debug;
	}
 
	function extend(namespace, delimiter) {
		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
		newDebug.log = this.log;
		return newDebug;
	}
 
	/**
	* Enables a debug mode by namespaces. This can include modes
	* separated by a colon and wildcards.
	*
	* @param {String} namespaces
	* @api public
	*/
	function enable(namespaces) {
		createDebug.save(namespaces);
		createDebug.namespaces = namespaces;
 
		createDebug.names = [];
		createDebug.skips = [];
 
		let i;
		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
		const len = split.length;
 
		for (i = 0; i < len; i++) {
			if (!split[i]) {
				// ignore empty strings
				continue;
			}
 
			namespaces = split[i].replace(/\*/g, '.*?');
 
			if (namespaces[0] === '-') {
				createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
			} else {
				createDebug.names.push(new RegExp('^' + namespaces + '$'));
			}
		}
	}
 
	/**
	* Disable debug output.
	*
	* @return {String} namespaces
	* @api public
	*/
	function disable() {
		const namespaces = [
			...createDebug.names.map(toNamespace),
			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
		].join(',');
		createDebug.enable('');
		return namespaces;
	}
 
	/**
	* Returns true if the given mode name is enabled, false otherwise.
	*
	* @param {String} name
	* @return {Boolean}
	* @api public
	*/
	function enabled(name) {
		if (name[name.length - 1] === '*') {
			return true;
		}
 
		let i;
		let len;
 
		for (i = 0, len = createDebug.skips.length; i < len; i++) {
			if (createDebug.skips[i].test(name)) {
				return false;
			}
		}
 
		for (i = 0, len = createDebug.names.length; i < len; i++) {
			if (createDebug.names[i].test(name)) {
				return true;
			}
		}
 
		return false;
	}
 
	/**
	* Convert regexp to namespace
	*
	* @param {RegExp} regxep
	* @return {String} namespace
	* @api private
	*/
	function toNamespace(regexp) {
		return regexp.toString()
			.substring(2, regexp.toString().length - 2)
			.replace(/\.\*\?$/, '*');
	}
 
	/**
	* Coerce `val`.
	*
	* @param {Mixed} val
	* @return {Mixed}
	* @api private
	*/
	function coerce(val) {
		if (val instanceof Error) {
			return val.stack || val.message;
		}
		return val;
	}
 
	/**
	* XXX DO NOT USE. This is a temporary stub function.
	* XXX It WILL be removed in the next major release.
	*/
	function destroy() {
		console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
	}
 
	createDebug.enable(createDebug.load());
 
	return createDebug;
}
 
module.exports = setup;
 
},{"ms":28}],23:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ERROR_PACKET = exports.PACKET_TYPES_REVERSE = exports.PACKET_TYPES = void 0;
const PACKET_TYPES = Object.create(null); // no Map = no polyfill
exports.PACKET_TYPES = PACKET_TYPES;
PACKET_TYPES["open"] = "0";
PACKET_TYPES["close"] = "1";
PACKET_TYPES["ping"] = "2";
PACKET_TYPES["pong"] = "3";
PACKET_TYPES["message"] = "4";
PACKET_TYPES["upgrade"] = "5";
PACKET_TYPES["noop"] = "6";
const PACKET_TYPES_REVERSE = Object.create(null);
exports.PACKET_TYPES_REVERSE = PACKET_TYPES_REVERSE;
Object.keys(PACKET_TYPES).forEach((key) => {
    PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
});
const ERROR_PACKET = { type: "error", data: "parser error" };
exports.ERROR_PACKET = ERROR_PACKET;
 
},{}],24:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decode = exports.encode = void 0;
// imported from https://github.com/socketio/base64-arraybuffer
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
const lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (let i = 0; i < chars.length; i++) {
    lookup[chars.charCodeAt(i)] = i;
}
const encode = (arraybuffer) => {
    let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
    for (i = 0; i < len; i += 3) {
        base64 += chars[bytes[i] >> 2];
        base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
        base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
        base64 += chars[bytes[i + 2] & 63];
    }
    if (len % 3 === 2) {
        base64 = base64.substring(0, base64.length - 1) + '=';
    }
    else if (len % 3 === 1) {
        base64 = base64.substring(0, base64.length - 2) + '==';
    }
    return base64;
};
exports.encode = encode;
const decode = (base64) => {
    let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
    if (base64[base64.length - 1] === '=') {
        bufferLength--;
        if (base64[base64.length - 2] === '=') {
            bufferLength--;
        }
    }
    const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
    for (i = 0; i < len; i += 4) {
        encoded1 = lookup[base64.charCodeAt(i)];
        encoded2 = lookup[base64.charCodeAt(i + 1)];
        encoded3 = lookup[base64.charCodeAt(i + 2)];
        encoded4 = lookup[base64.charCodeAt(i + 3)];
        bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
        bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
        bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
    }
    return arraybuffer;
};
exports.decode = decode;
 
},{}],25:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodePacket = void 0;
const commons_js_1 = require("./commons.js");
const base64_arraybuffer_js_1 = require("./contrib/base64-arraybuffer.js");
const withNativeArrayBuffer = typeof ArrayBuffer === "function";
const decodePacket = (encodedPacket, binaryType) => {
    if (typeof encodedPacket !== "string") {
        return {
            type: "message",
            data: mapBinary(encodedPacket, binaryType),
        };
    }
    const type = encodedPacket.charAt(0);
    if (type === "b") {
        return {
            type: "message",
            data: decodeBase64Packet(encodedPacket.substring(1), binaryType),
        };
    }
    const packetType = commons_js_1.PACKET_TYPES_REVERSE[type];
    if (!packetType) {
        return commons_js_1.ERROR_PACKET;
    }
    return encodedPacket.length > 1
        ? {
            type: commons_js_1.PACKET_TYPES_REVERSE[type],
            data: encodedPacket.substring(1),
        }
        : {
            type: commons_js_1.PACKET_TYPES_REVERSE[type],
        };
};
exports.decodePacket = decodePacket;
const decodeBase64Packet = (data, binaryType) => {
    if (withNativeArrayBuffer) {
        const decoded = (0, base64_arraybuffer_js_1.decode)(data);
        return mapBinary(decoded, binaryType);
    }
    else {
        return { base64: true, data }; // fallback for old browsers
    }
};
const mapBinary = (data, binaryType) => {
    switch (binaryType) {
        case "blob":
            if (data instanceof Blob) {
                // from WebSocket + binaryType "blob"
                return data;
            }
            else {
                // from HTTP long-polling or WebTransport
                return new Blob([data]);
            }
        case "arraybuffer":
        default:
            if (data instanceof ArrayBuffer) {
                // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
                return data;
            }
            else {
                // from WebTransport (Uint8Array)
                return data.buffer;
            }
    }
};
 
},{"./commons.js":23,"./contrib/base64-arraybuffer.js":24}],26:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodePacket = void 0;
exports.encodePacketToBinary = encodePacketToBinary;
const commons_js_1 = require("./commons.js");
const withNativeBlob = typeof Blob === "function" ||
    (typeof Blob !== "undefined" &&
        Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
const withNativeArrayBuffer = typeof ArrayBuffer === "function";
// ArrayBuffer.isView method is not defined in IE10
const isView = (obj) => {
    return typeof ArrayBuffer.isView === "function"
        ? ArrayBuffer.isView(obj)
        : obj && obj.buffer instanceof ArrayBuffer;
};
const encodePacket = ({ type, data }, supportsBinary, callback) => {
    if (withNativeBlob && data instanceof Blob) {
        if (supportsBinary) {
            return callback(data);
        }
        else {
            return encodeBlobAsBase64(data, callback);
        }
    }
    else if (withNativeArrayBuffer &&
        (data instanceof ArrayBuffer || isView(data))) {
        if (supportsBinary) {
            return callback(data);
        }
        else {
            return encodeBlobAsBase64(new Blob([data]), callback);
        }
    }
    // plain string
    return callback(commons_js_1.PACKET_TYPES[type] + (data || ""));
};
exports.encodePacket = encodePacket;
const encodeBlobAsBase64 = (data, callback) => {
    const fileReader = new FileReader();
    fileReader.onload = function () {
        const content = fileReader.result.split(",")[1];
        callback("b" + (content || ""));
    };
    return fileReader.readAsDataURL(data);
};
function toArray(data) {
    if (data instanceof Uint8Array) {
        return data;
    }
    else if (data instanceof ArrayBuffer) {
        return new Uint8Array(data);
    }
    else {
        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
    }
}
let TEXT_ENCODER;
function encodePacketToBinary(packet, callback) {
    if (withNativeBlob && packet.data instanceof Blob) {
        return packet.data.arrayBuffer().then(toArray).then(callback);
    }
    else if (withNativeArrayBuffer &&
        (packet.data instanceof ArrayBuffer || isView(packet.data))) {
        return callback(toArray(packet.data));
    }
    encodePacket(packet, false, (encoded) => {
        if (!TEXT_ENCODER) {
            TEXT_ENCODER = new TextEncoder();
        }
        callback(TEXT_ENCODER.encode(encoded));
    });
}
 
},{"./commons.js":23}],27:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodePayload = exports.decodePacket = exports.encodePayload = exports.encodePacket = exports.protocol = void 0;
exports.createPacketEncoderStream = createPacketEncoderStream;
exports.createPacketDecoderStream = createPacketDecoderStream;
const encodePacket_js_1 = require("./encodePacket.js");
Object.defineProperty(exports, "encodePacket", { enumerable: true, get: function () { return encodePacket_js_1.encodePacket; } });
const decodePacket_js_1 = require("./decodePacket.js");
Object.defineProperty(exports, "decodePacket", { enumerable: true, get: function () { return decodePacket_js_1.decodePacket; } });
const commons_js_1 = require("./commons.js");
const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
const encodePayload = (packets, callback) => {
    // some packets may be added to the array while encoding, so the initial length must be saved
    const length = packets.length;
    const encodedPackets = new Array(length);
    let count = 0;
    packets.forEach((packet, i) => {
        // force base64 encoding for binary packets
        (0, encodePacket_js_1.encodePacket)(packet, false, (encodedPacket) => {
            encodedPackets[i] = encodedPacket;
            if (++count === length) {
                callback(encodedPackets.join(SEPARATOR));
            }
        });
    });
};
exports.encodePayload = encodePayload;
const decodePayload = (encodedPayload, binaryType) => {
    const encodedPackets = encodedPayload.split(SEPARATOR);
    const packets = [];
    for (let i = 0; i < encodedPackets.length; i++) {
        const decodedPacket = (0, decodePacket_js_1.decodePacket)(encodedPackets[i], binaryType);
        packets.push(decodedPacket);
        if (decodedPacket.type === "error") {
            break;
        }
    }
    return packets;
};
exports.decodePayload = decodePayload;
function createPacketEncoderStream() {
    return new TransformStream({
        transform(packet, controller) {
            (0, encodePacket_js_1.encodePacketToBinary)(packet, (encodedPacket) => {
                const payloadLength = encodedPacket.length;
                let header;
                // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length
                if (payloadLength < 126) {
                    header = new Uint8Array(1);
                    new DataView(header.buffer).setUint8(0, payloadLength);
                }
                else if (payloadLength < 65536) {
                    header = new Uint8Array(3);
                    const view = new DataView(header.buffer);
                    view.setUint8(0, 126);
                    view.setUint16(1, payloadLength);
                }
                else {
                    header = new Uint8Array(9);
                    const view = new DataView(header.buffer);
                    view.setUint8(0, 127);
                    view.setBigUint64(1, BigInt(payloadLength));
                }
                // first bit indicates whether the payload is plain text (0) or binary (1)
                if (packet.data && typeof packet.data !== "string") {
                    header[0] |= 0x80;
                }
                controller.enqueue(header);
                controller.enqueue(encodedPacket);
            });
        },
    });
}
let TEXT_DECODER;
function totalLength(chunks) {
    return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
}
function concatChunks(chunks, size) {
    if (chunks[0].length === size) {
        return chunks.shift();
    }
    const buffer = new Uint8Array(size);
    let j = 0;
    for (let i = 0; i < size; i++) {
        buffer[i] = chunks[0][j++];
        if (j === chunks[0].length) {
            chunks.shift();
            j = 0;
        }
    }
    if (chunks.length && j < chunks[0].length) {
        chunks[0] = chunks[0].slice(j);
    }
    return buffer;
}
function createPacketDecoderStream(maxPayload, binaryType) {
    if (!TEXT_DECODER) {
        TEXT_DECODER = new TextDecoder();
    }
    const chunks = [];
    let state = 0 /* State.READ_HEADER */;
    let expectedLength = -1;
    let isBinary = false;
    return new TransformStream({
        transform(chunk, controller) {
            chunks.push(chunk);
            while (true) {
                if (state === 0 /* State.READ_HEADER */) {
                    if (totalLength(chunks) < 1) {
                        break;
                    }
                    const header = concatChunks(chunks, 1);
                    isBinary = (header[0] & 0x80) === 0x80;
                    expectedLength = header[0] & 0x7f;
                    if (expectedLength < 126) {
                        state = 3 /* State.READ_PAYLOAD */;
                    }
                    else if (expectedLength === 126) {
                        state = 1 /* State.READ_EXTENDED_LENGTH_16 */;
                    }
                    else {
                        state = 2 /* State.READ_EXTENDED_LENGTH_64 */;
                    }
                }
                else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {
                    if (totalLength(chunks) < 2) {
                        break;
                    }
                    const headerArray = concatChunks(chunks, 2);
                    expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
                    state = 3 /* State.READ_PAYLOAD */;
                }
                else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {
                    if (totalLength(chunks) < 8) {
                        break;
                    }
                    const headerArray = concatChunks(chunks, 8);
                    const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
                    const n = view.getUint32(0);
                    if (n > Math.pow(2, 53 - 32) - 1) {
                        // the maximum safe integer in JavaScript is 2^53 - 1
                        controller.enqueue(commons_js_1.ERROR_PACKET);
                        break;
                    }
                    expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
                    state = 3 /* State.READ_PAYLOAD */;
                }
                else {
                    if (totalLength(chunks) < expectedLength) {
                        break;
                    }
                    const data = concatChunks(chunks, expectedLength);
                    controller.enqueue((0, decodePacket_js_1.decodePacket)(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
                    state = 0 /* State.READ_HEADER */;
                }
                if (expectedLength === 0 || expectedLength > maxPayload) {
                    controller.enqueue(commons_js_1.ERROR_PACKET);
                    break;
                }
            }
        },
    });
}
exports.protocol = 4;
 
},{"./commons.js":23,"./decodePacket.js":25,"./encodePacket.js":26}],28:[function(require,module,exports){
/**
 * Helpers.
 */
 
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
 
/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} [options]
 * @throws {Error} throw an error if val is not a non-empty string or a number
 * @return {String|Number}
 * @api public
 */
 
module.exports = function (val, options) {
  options = options || {};
  var type = typeof val;
  if (type === 'string' && val.length > 0) {
    return parse(val);
  } else if (type === 'number' && isFinite(val)) {
    return options.long ? fmtLong(val) : fmtShort(val);
  }
  throw new Error(
    'val is not a non-empty string or a valid number. val=' +
      JSON.stringify(val)
  );
};
 
/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */
 
function parse(str) {
  str = String(str);
  if (str.length > 100) {
    return;
  }
  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
    str
  );
  if (!match) {
    return;
  }
  var n = parseFloat(match[1]);
  var type = (match[2] || 'ms').toLowerCase();
  switch (type) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return n * y;
    case 'weeks':
    case 'week':
    case 'w':
      return n * w;
    case 'days':
    case 'day':
    case 'd':
      return n * d;
    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return n * h;
    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return n * m;
    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return n * s;
    case 'milliseconds':
    case 'millisecond':
    case 'msecs':
    case 'msec':
    case 'ms':
      return n;
    default:
      return undefined;
  }
}
 
/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */
 
function fmtShort(ms) {
  var msAbs = Math.abs(ms);
  if (msAbs >= d) {
    return Math.round(ms / d) + 'd';
  }
  if (msAbs >= h) {
    return Math.round(ms / h) + 'h';
  }
  if (msAbs >= m) {
    return Math.round(ms / m) + 'm';
  }
  if (msAbs >= s) {
    return Math.round(ms / s) + 's';
  }
  return ms + 'ms';
}
 
/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */
 
function fmtLong(ms) {
  var msAbs = Math.abs(ms);
  if (msAbs >= d) {
    return plural(ms, msAbs, d, 'day');
  }
  if (msAbs >= h) {
    return plural(ms, msAbs, h, 'hour');
  }
  if (msAbs >= m) {
    return plural(ms, msAbs, m, 'minute');
  }
  if (msAbs >= s) {
    return plural(ms, msAbs, s, 'second');
  }
  return ms + ' ms';
}
 
/**
 * Pluralization helper.
 */
 
function plural(ms, msAbs, n, name) {
  var isPlural = msAbs >= n * 1.5;
  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
 
},{}],29:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
 
// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.
 
var cachedSetTimeout;
var cachedClearTimeout;
 
function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }
 
 
}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }
 
 
 
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
 
function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}
 
function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;
 
    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}
 
process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};
 
// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
 
function noop() {}
 
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
 
process.listeners = function (name) { return [] }
 
process.binding = function (name) {
    throw new Error('process.binding is not supported');
};
 
process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
 
},{}],30:[function(require,module,exports){
"use strict";
/**
 * Initialize backoff timer with `opts`.
 *
 * - `min` initial timeout in milliseconds [100]
 * - `max` max timeout [10000]
 * - `jitter` [0]
 * - `factor` [2]
 *
 * @param {Object} opts
 * @api public
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.Backoff = Backoff;
function Backoff(opts) {
    opts = opts || {};
    this.ms = opts.min || 100;
    this.max = opts.max || 10000;
    this.factor = opts.factor || 2;
    this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
    this.attempts = 0;
}
/**
 * Return the backoff duration.
 *
 * @return {Number}
 * @api public
 */
Backoff.prototype.duration = function () {
    var ms = this.ms * Math.pow(this.factor, this.attempts++);
    if (this.jitter) {
        var rand = Math.random();
        var deviation = Math.floor(rand * this.jitter * ms);
        ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
    }
    return Math.min(ms, this.max) | 0;
};
/**
 * Reset the number of attempts.
 *
 * @api public
 */
Backoff.prototype.reset = function () {
    this.attempts = 0;
};
/**
 * Set the minimum duration
 *
 * @api public
 */
Backoff.prototype.setMin = function (min) {
    this.ms = min;
};
/**
 * Set the maximum duration
 *
 * @api public
 */
Backoff.prototype.setMax = function (max) {
    this.max = max;
};
/**
 * Set the jitter
 *
 * @api public
 */
Backoff.prototype.setJitter = function (jitter) {
    this.jitter = jitter;
};
 
},{}],31:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebTransport = exports.WebSocket = exports.NodeWebSocket = exports.XHR = exports.NodeXHR = exports.Fetch = exports.Socket = exports.Manager = exports.protocol = void 0;
exports.io = lookup;
exports.connect = lookup;
exports.default = lookup;
const url_js_1 = require("./url.js");
const manager_js_1 = require("./manager.js");
Object.defineProperty(exports, "Manager", { enumerable: true, get: function () { return manager_js_1.Manager; } });
const socket_js_1 = require("./socket.js");
Object.defineProperty(exports, "Socket", { enumerable: true, get: function () { return socket_js_1.Socket; } });
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("socket.io-client"); // debug()
/**
 * Managers cache.
 */
const cache = {};
function lookup(uri, opts) {
    if (typeof uri === "object") {
        opts = uri;
        uri = undefined;
    }
    opts = opts || {};
    const parsed = (0, url_js_1.url)(uri, opts.path || "/socket.io");
    const source = parsed.source;
    const id = parsed.id;
    const path = parsed.path;
    const sameNamespace = cache[id] && path in cache[id]["nsps"];
    const newConnection = opts.forceNew ||
        opts["force new connection"] ||
        false === opts.multiplex ||
        sameNamespace;
    let io;
    if (newConnection) {
        debug("ignoring socket cache for %s", source);
        io = new manager_js_1.Manager(source, opts);
    }
    else {
        if (!cache[id]) {
            debug("new io instance for %s", source);
            cache[id] = new manager_js_1.Manager(source, opts);
        }
        io = cache[id];
    }
    if (parsed.query && !opts.query) {
        opts.query = parsed.queryKey;
    }
    return io.socket(parsed.path, opts);
}
// so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
// namespace (e.g. `io.connect(...)`), for backward compatibility
Object.assign(lookup, {
    Manager: manager_js_1.Manager,
    Socket: socket_js_1.Socket,
    io: lookup,
    connect: lookup,
});
/**
 * Protocol version.
 *
 * @public
 */
var socket_io_parser_1 = require("socket.io-parser");
Object.defineProperty(exports, "protocol", { enumerable: true, get: function () { return socket_io_parser_1.protocol; } });
var engine_io_client_1 = require("engine.io-client");
Object.defineProperty(exports, "Fetch", { enumerable: true, get: function () { return engine_io_client_1.Fetch; } });
Object.defineProperty(exports, "NodeXHR", { enumerable: true, get: function () { return engine_io_client_1.NodeXHR; } });
Object.defineProperty(exports, "XHR", { enumerable: true, get: function () { return engine_io_client_1.XHR; } });
Object.defineProperty(exports, "NodeWebSocket", { enumerable: true, get: function () { return engine_io_client_1.NodeWebSocket; } });
Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function () { return engine_io_client_1.WebSocket; } });
Object.defineProperty(exports, "WebTransport", { enumerable: true, get: function () { return engine_io_client_1.WebTransport; } });
 
module.exports = lookup;
 
},{"./manager.js":32,"./socket.js":34,"./url.js":35,"debug":36,"engine.io-client":11,"socket.io-parser":39}],32:[function(require,module,exports){
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Manager = void 0;
const engine_io_client_1 = require("engine.io-client");
const socket_js_1 = require("./socket.js");
const parser = __importStar(require("socket.io-parser"));
const on_js_1 = require("./on.js");
const backo2_js_1 = require("./contrib/backo2.js");
const component_emitter_1 = require("@socket.io/component-emitter");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("socket.io-client:manager"); // debug()
class Manager extends component_emitter_1.Emitter {
    constructor(uri, opts) {
        var _a;
        super();
        this.nsps = {};
        this.subs = [];
        if (uri && "object" === typeof uri) {
            opts = uri;
            uri = undefined;
        }
        opts = opts || {};
        opts.path = opts.path || "/socket.io";
        this.opts = opts;
        (0, engine_io_client_1.installTimerFunctions)(this, opts);
        this.reconnection(opts.reconnection !== false);
        this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
        this.reconnectionDelay(opts.reconnectionDelay || 1000);
        this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
        this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
        this.backoff = new backo2_js_1.Backoff({
            min: this.reconnectionDelay(),
            max: this.reconnectionDelayMax(),
            jitter: this.randomizationFactor(),
        });
        this.timeout(null == opts.timeout ? 20000 : opts.timeout);
        this._readyState = "closed";
        this.uri = uri;
        const _parser = opts.parser || parser;
        this.encoder = new _parser.Encoder();
        this.decoder = new _parser.Decoder();
        this._autoConnect = opts.autoConnect !== false;
        if (this._autoConnect)
            this.open();
    }
    reconnection(v) {
        if (!arguments.length)
            return this._reconnection;
        this._reconnection = !!v;
        if (!v) {
            this.skipReconnect = true;
        }
        return this;
    }
    reconnectionAttempts(v) {
        if (v === undefined)
            return this._reconnectionAttempts;
        this._reconnectionAttempts = v;
        return this;
    }
    reconnectionDelay(v) {
        var _a;
        if (v === undefined)
            return this._reconnectionDelay;
        this._reconnectionDelay = v;
        (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
        return this;
    }
    randomizationFactor(v) {
        var _a;
        if (v === undefined)
            return this._randomizationFactor;
        this._randomizationFactor = v;
        (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
        return this;
    }
    reconnectionDelayMax(v) {
        var _a;
        if (v === undefined)
            return this._reconnectionDelayMax;
        this._reconnectionDelayMax = v;
        (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
        return this;
    }
    timeout(v) {
        if (!arguments.length)
            return this._timeout;
        this._timeout = v;
        return this;
    }
    /**
     * Starts trying to reconnect if reconnection is enabled and we have not
     * started reconnecting yet
     *
     * @private
     */
    maybeReconnectOnOpen() {
        // Only try to reconnect if it's the first time we're connecting
        if (!this._reconnecting &&
            this._reconnection &&
            this.backoff.attempts === 0) {
            // keeps reconnection from firing twice for the same reconnection loop
            this.reconnect();
        }
    }
    /**
     * Sets the current transport `socket`.
     *
     * @param {Function} fn - optional, callback
     * @return self
     * @public
     */
    open(fn) {
        debug("readyState %s", this._readyState);
        if (~this._readyState.indexOf("open"))
            return this;
        debug("opening %s", this.uri);
        this.engine = new engine_io_client_1.Socket(this.uri, this.opts);
        const socket = this.engine;
        const self = this;
        this._readyState = "opening";
        this.skipReconnect = false;
        // emit `open`
        const openSubDestroy = (0, on_js_1.on)(socket, "open", function () {
            self.onopen();
            fn && fn();
        });
        const onError = (err) => {
            debug("error");
            this.cleanup();
            this._readyState = "closed";
            this.emitReserved("error", err);
            if (fn) {
                fn(err);
            }
            else {
                // Only do this if there is no fn to handle the error
                this.maybeReconnectOnOpen();
            }
        };
        // emit `error`
        const errorSub = (0, on_js_1.on)(socket, "error", onError);
        if (false !== this._timeout) {
            const timeout = this._timeout;
            debug("connect attempt will timeout after %d", timeout);
            // set timer
            const timer = this.setTimeoutFn(() => {
                debug("connect attempt timed out after %d", timeout);
                openSubDestroy();
                onError(new Error("timeout"));
                socket.close();
            }, timeout);
            if (this.opts.autoUnref) {
                timer.unref();
            }
            this.subs.push(() => {
                this.clearTimeoutFn(timer);
            });
        }
        this.subs.push(openSubDestroy);
        this.subs.push(errorSub);
        return this;
    }
    /**
     * Alias for open()
     *
     * @return self
     * @public
     */
    connect(fn) {
        return this.open(fn);
    }
    /**
     * Called upon transport open.
     *
     * @private
     */
    onopen() {
        debug("open");
        // clear old subs
        this.cleanup();
        // mark as open
        this._readyState = "open";
        this.emitReserved("open");
        // add new subs
        const socket = this.engine;
        this.subs.push((0, on_js_1.on)(socket, "ping", this.onping.bind(this)), (0, on_js_1.on)(socket, "data", this.ondata.bind(this)), (0, on_js_1.on)(socket, "error", this.onerror.bind(this)), (0, on_js_1.on)(socket, "close", this.onclose.bind(this)), 
        // @ts-ignore
        (0, on_js_1.on)(this.decoder, "decoded", this.ondecoded.bind(this)));
    }
    /**
     * Called upon a ping.
     *
     * @private
     */
    onping() {
        this.emitReserved("ping");
    }
    /**
     * Called with data.
     *
     * @private
     */
    ondata(data) {
        try {
            this.decoder.add(data);
        }
        catch (e) {
            this.onclose("parse error", e);
        }
    }
    /**
     * Called when parser fully decodes a packet.
     *
     * @private
     */
    ondecoded(packet) {
        // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
        (0, engine_io_client_1.nextTick)(() => {
            this.emitReserved("packet", packet);
        }, this.setTimeoutFn);
    }
    /**
     * Called upon socket error.
     *
     * @private
     */
    onerror(err) {
        debug("error", err);
        this.emitReserved("error", err);
    }
    /**
     * Creates a new socket for the given `nsp`.
     *
     * @return {Socket}
     * @public
     */
    socket(nsp, opts) {
        let socket = this.nsps[nsp];
        if (!socket) {
            socket = new socket_js_1.Socket(this, nsp, opts);
            this.nsps[nsp] = socket;
        }
        else if (this._autoConnect && !socket.active) {
            socket.connect();
        }
        return socket;
    }
    /**
     * Called upon a socket close.
     *
     * @param socket
     * @private
     */
    _destroy(socket) {
        const nsps = Object.keys(this.nsps);
        for (const nsp of nsps) {
            const socket = this.nsps[nsp];
            if (socket.active) {
                debug("socket %s is still active, skipping close", nsp);
                return;
            }
        }
        this._close();
    }
    /**
     * Writes a packet.
     *
     * @param packet
     * @private
     */
    _packet(packet) {
        debug("writing packet %j", packet);
        const encodedPackets = this.encoder.encode(packet);
        for (let i = 0; i < encodedPackets.length; i++) {
            this.engine.write(encodedPackets[i], packet.options);
        }
    }
    /**
     * Clean up transport subscriptions and packet buffer.
     *
     * @private
     */
    cleanup() {
        debug("cleanup");
        this.subs.forEach((subDestroy) => subDestroy());
        this.subs.length = 0;
        this.decoder.destroy();
    }
    /**
     * Close the current socket.
     *
     * @private
     */
    _close() {
        debug("disconnect");
        this.skipReconnect = true;
        this._reconnecting = false;
        this.onclose("forced close");
    }
    /**
     * Alias for close()
     *
     * @private
     */
    disconnect() {
        return this._close();
    }
    /**
     * Called when:
     *
     * - the low-level engine is closed
     * - the parser encountered a badly formatted packet
     * - all sockets are disconnected
     *
     * @private
     */
    onclose(reason, description) {
        var _a;
        debug("closed due to %s", reason);
        this.cleanup();
        (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
        this.backoff.reset();
        this._readyState = "closed";
        this.emitReserved("close", reason, description);
        if (this._reconnection && !this.skipReconnect) {
            this.reconnect();
        }
    }
    /**
     * Attempt a reconnection.
     *
     * @private
     */
    reconnect() {
        if (this._reconnecting || this.skipReconnect)
            return this;
        const self = this;
        if (this.backoff.attempts >= this._reconnectionAttempts) {
            debug("reconnect failed");
            this.backoff.reset();
            this.emitReserved("reconnect_failed");
            this._reconnecting = false;
        }
        else {
            const delay = this.backoff.duration();
            debug("will wait %dms before reconnect attempt", delay);
            this._reconnecting = true;
            const timer = this.setTimeoutFn(() => {
                if (self.skipReconnect)
                    return;
                debug("attempting reconnect");
                this.emitReserved("reconnect_attempt", self.backoff.attempts);
                // check again for the case socket closed in above events
                if (self.skipReconnect)
                    return;
                self.open((err) => {
                    if (err) {
                        debug("reconnect attempt error");
                        self._reconnecting = false;
                        self.reconnect();
                        this.emitReserved("reconnect_error", err);
                    }
                    else {
                        debug("reconnect success");
                        self.onreconnect();
                    }
                });
            }, delay);
            if (this.opts.autoUnref) {
                timer.unref();
            }
            this.subs.push(() => {
                this.clearTimeoutFn(timer);
            });
        }
    }
    /**
     * Called upon successful reconnect.
     *
     * @private
     */
    onreconnect() {
        const attempt = this.backoff.attempts;
        this._reconnecting = false;
        this.backoff.reset();
        this.emitReserved("reconnect", attempt);
    }
}
exports.Manager = Manager;
 
},{"./contrib/backo2.js":30,"./on.js":33,"./socket.js":34,"@socket.io/component-emitter":6,"debug":36,"engine.io-client":11,"socket.io-parser":39}],33:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.on = on;
function on(obj, ev, fn) {
    obj.on(ev, fn);
    return function subDestroy() {
        obj.off(ev, fn);
    };
}
 
},{}],34:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Socket = void 0;
const socket_io_parser_1 = require("socket.io-parser");
const on_js_1 = require("./on.js");
const component_emitter_1 = require("@socket.io/component-emitter");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("socket.io-client:socket"); // debug()
/**
 * Internal events.
 * These events can't be emitted by the user.
 */
const RESERVED_EVENTS = Object.freeze({
    connect: 1,
    connect_error: 1,
    disconnect: 1,
    disconnecting: 1,
    // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
    newListener: 1,
    removeListener: 1,
});
/**
 * A Socket is the fundamental class for interacting with the server.
 *
 * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
 *
 * @example
 * const socket = io();
 *
 * socket.on("connect", () => {
 *   console.log("connected");
 * });
 *
 * // send an event to the server
 * socket.emit("foo", "bar");
 *
 * socket.on("foobar", () => {
 *   // an event was received from the server
 * });
 *
 * // upon disconnection
 * socket.on("disconnect", (reason) => {
 *   console.log(`disconnected due to ${reason}`);
 * });
 */
class Socket extends component_emitter_1.Emitter {
    /**
     * `Socket` constructor.
     */
    constructor(io, nsp, opts) {
        super();
        /**
         * Whether the socket is currently connected to the server.
         *
         * @example
         * const socket = io();
         *
         * socket.on("connect", () => {
         *   console.log(socket.connected); // true
         * });
         *
         * socket.on("disconnect", () => {
         *   console.log(socket.connected); // false
         * });
         */
        this.connected = false;
        /**
         * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
         * be transmitted by the server.
         */
        this.recovered = false;
        /**
         * Buffer for packets received before the CONNECT packet
         */
        this.receiveBuffer = [];
        /**
         * Buffer for packets that will be sent once the socket is connected
         */
        this.sendBuffer = [];
        /**
         * The queue of packets to be sent with retry in case of failure.
         *
         * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
         * @private
         */
        this._queue = [];
        /**
         * A sequence to generate the ID of the {@link QueuedPacket}.
         * @private
         */
        this._queueSeq = 0;
        this.ids = 0;
        /**
         * A map containing acknowledgement handlers.
         *
         * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
         *
         * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
         * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
         * - `const value = await socket.emitWithAck("test")`
         *
         * From those that don't:
         *
         * - `socket.emit("test", (value) => { ... });`
         *
         * In the first case, the handlers will be called with an error when:
         *
         * - the timeout is reached
         * - the socket gets disconnected
         *
         * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
         * an acknowledgement from the server.
         *
         * @private
         */
        this.acks = {};
        this.flags = {};
        this.io = io;
        this.nsp = nsp;
        if (opts && opts.auth) {
            this.auth = opts.auth;
        }
        this._opts = Object.assign({}, opts);
        if (this.io._autoConnect)
            this.open();
    }
    /**
     * Whether the socket is currently disconnected
     *
     * @example
     * const socket = io();
     *
     * socket.on("connect", () => {
     *   console.log(socket.disconnected); // false
     * });
     *
     * socket.on("disconnect", () => {
     *   console.log(socket.disconnected); // true
     * });
     */
    get disconnected() {
        return !this.connected;
    }
    /**
     * Subscribe to open, close and packet events
     *
     * @private
     */
    subEvents() {
        if (this.subs)
            return;
        const io = this.io;
        this.subs = [
            (0, on_js_1.on)(io, "open", this.onopen.bind(this)),
            (0, on_js_1.on)(io, "packet", this.onpacket.bind(this)),
            (0, on_js_1.on)(io, "error", this.onerror.bind(this)),
            (0, on_js_1.on)(io, "close", this.onclose.bind(this)),
        ];
    }
    /**
     * Whether the Socket will try to reconnect when its Manager connects or reconnects.
     *
     * @example
     * const socket = io();
     *
     * console.log(socket.active); // true
     *
     * socket.on("disconnect", (reason) => {
     *   if (reason === "io server disconnect") {
     *     // the disconnection was initiated by the server, you need to manually reconnect
     *     console.log(socket.active); // false
     *   }
     *   // else the socket will automatically try to reconnect
     *   console.log(socket.active); // true
     * });
     */
    get active() {
        return !!this.subs;
    }
    /**
     * "Opens" the socket.
     *
     * @example
     * const socket = io({
     *   autoConnect: false
     * });
     *
     * socket.connect();
     */
    connect() {
        if (this.connected)
            return this;
        this.subEvents();
        if (!this.io["_reconnecting"])
            this.io.open(); // ensure open
        if ("open" === this.io._readyState)
            this.onopen();
        return this;
    }
    /**
     * Alias for {@link connect()}.
     */
    open() {
        return this.connect();
    }
    /**
     * Sends a `message` event.
     *
     * This method mimics the WebSocket.send() method.
     *
     * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
     *
     * @example
     * socket.send("hello");
     *
     * // this is equivalent to
     * socket.emit("message", "hello");
     *
     * @return self
     */
    send(...args) {
        args.unshift("message");
        this.emit.apply(this, args);
        return this;
    }
    /**
     * Override `emit`.
     * If the event is in `events`, it's emitted normally.
     *
     * @example
     * socket.emit("hello", "world");
     *
     * // all serializable datastructures are supported (no need to call JSON.stringify)
     * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
     *
     * // with an acknowledgement from the server
     * socket.emit("hello", "world", (val) => {
     *   // ...
     * });
     *
     * @return self
     */
    emit(ev, ...args) {
        var _a, _b, _c;
        if (RESERVED_EVENTS.hasOwnProperty(ev)) {
            throw new Error('"' + ev.toString() + '" is a reserved event name');
        }
        args.unshift(ev);
        if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
            this._addToQueue(args);
            return this;
        }
        const packet = {
            type: socket_io_parser_1.PacketType.EVENT,
            data: args,
        };
        packet.options = {};
        packet.options.compress = this.flags.compress !== false;
        // event ack callback
        if ("function" === typeof args[args.length - 1]) {
            const id = this.ids++;
            debug("emitting packet with ack id %d", id);
            const ack = args.pop();
            this._registerAckCallback(id, ack);
            packet.id = id;
        }
        const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
        const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
        const discardPacket = this.flags.volatile && !isTransportWritable;
        if (discardPacket) {
            debug("discard packet as the transport is not currently writable");
        }
        else if (isConnected) {
            this.notifyOutgoingListeners(packet);
            this.packet(packet);
        }
        else {
            this.sendBuffer.push(packet);
        }
        this.flags = {};
        return this;
    }
    /**
     * @private
     */
    _registerAckCallback(id, ack) {
        var _a;
        const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
        if (timeout === undefined) {
            this.acks[id] = ack;
            return;
        }
        // @ts-ignore
        const timer = this.io.setTimeoutFn(() => {
            delete this.acks[id];
            for (let i = 0; i < this.sendBuffer.length; i++) {
                if (this.sendBuffer[i].id === id) {
                    debug("removing packet with ack id %d from the buffer", id);
                    this.sendBuffer.splice(i, 1);
                }
            }
            debug("event with ack id %d has timed out after %d ms", id, timeout);
            ack.call(this, new Error("operation has timed out"));
        }, timeout);
        const fn = (...args) => {
            // @ts-ignore
            this.io.clearTimeoutFn(timer);
            ack.apply(this, args);
        };
        fn.withError = true;
        this.acks[id] = fn;
    }
    /**
     * Emits an event and waits for an acknowledgement
     *
     * @example
     * // without timeout
     * const response = await socket.emitWithAck("hello", "world");
     *
     * // with a specific timeout
     * try {
     *   const response = await socket.timeout(1000).emitWithAck("hello", "world");
     * } catch (err) {
     *   // the server did not acknowledge the event in the given delay
     * }
     *
     * @return a Promise that will be fulfilled when the server acknowledges the event
     */
    emitWithAck(ev, ...args) {
        return new Promise((resolve, reject) => {
            const fn = (arg1, arg2) => {
                return arg1 ? reject(arg1) : resolve(arg2);
            };
            fn.withError = true;
            args.push(fn);
            this.emit(ev, ...args);
        });
    }
    /**
     * Add the packet to the queue.
     * @param args
     * @private
     */
    _addToQueue(args) {
        let ack;
        if (typeof args[args.length - 1] === "function") {
            ack = args.pop();
        }
        const packet = {
            id: this._queueSeq++,
            tryCount: 0,
            pending: false,
            args,
            flags: Object.assign({ fromQueue: true }, this.flags),
        };
        args.push((err, ...responseArgs) => {
            if (packet !== this._queue[0]) {
                // the packet has already been acknowledged
                return;
            }
            const hasError = err !== null;
            if (hasError) {
                if (packet.tryCount > this._opts.retries) {
                    debug("packet [%d] is discarded after %d tries", packet.id, packet.tryCount);
                    this._queue.shift();
                    if (ack) {
                        ack(err);
                    }
                }
            }
            else {
                debug("packet [%d] was successfully sent", packet.id);
                this._queue.shift();
                if (ack) {
                    ack(null, ...responseArgs);
                }
            }
            packet.pending = false;
            return this._drainQueue();
        });
        this._queue.push(packet);
        this._drainQueue();
    }
    /**
     * Send the first packet of the queue, and wait for an acknowledgement from the server.
     * @param force - whether to resend a packet that has not been acknowledged yet
     *
     * @private
     */
    _drainQueue(force = false) {
        debug("draining queue");
        if (!this.connected || this._queue.length === 0) {
            return;
        }
        const packet = this._queue[0];
        if (packet.pending && !force) {
            debug("packet [%d] has already been sent and is waiting for an ack", packet.id);
            return;
        }
        packet.pending = true;
        packet.tryCount++;
        debug("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
        this.flags = packet.flags;
        this.emit.apply(this, packet.args);
    }
    /**
     * Sends a packet.
     *
     * @param packet
     * @private
     */
    packet(packet) {
        packet.nsp = this.nsp;
        this.io._packet(packet);
    }
    /**
     * Called upon engine `open`.
     *
     * @private
     */
    onopen() {
        debug("transport is open - connecting");
        if (typeof this.auth == "function") {
            this.auth((data) => {
                this._sendConnectPacket(data);
            });
        }
        else {
            this._sendConnectPacket(this.auth);
        }
    }
    /**
     * Sends a CONNECT packet to initiate the Socket.IO session.
     *
     * @param data
     * @private
     */
    _sendConnectPacket(data) {
        this.packet({
            type: socket_io_parser_1.PacketType.CONNECT,
            data: this._pid
                ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
                : data,
        });
    }
    /**
     * Called upon engine or manager `error`.
     *
     * @param err
     * @private
     */
    onerror(err) {
        if (!this.connected) {
            this.emitReserved("connect_error", err);
        }
    }
    /**
     * Called upon engine `close`.
     *
     * @param reason
     * @param description
     * @private
     */
    onclose(reason, description) {
        debug("close (%s)", reason);
        this.connected = false;
        delete this.id;
        this.emitReserved("disconnect", reason, description);
        this._clearAcks();
    }
    /**
     * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
     * the server.
     *
     * @private
     */
    _clearAcks() {
        Object.keys(this.acks).forEach((id) => {
            const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
            if (!isBuffered) {
                // note: handlers that do not accept an error as first argument are ignored here
                const ack = this.acks[id];
                delete this.acks[id];
                if (ack.withError) {
                    ack.call(this, new Error("socket has been disconnected"));
                }
            }
        });
    }
    /**
     * Called with socket packet.
     *
     * @param packet
     * @private
     */
    onpacket(packet) {
        const sameNamespace = packet.nsp === this.nsp;
        if (!sameNamespace)
            return;
        switch (packet.type) {
            case socket_io_parser_1.PacketType.CONNECT:
                if (packet.data && packet.data.sid) {
                    this.onconnect(packet.data.sid, packet.data.pid);
                }
                else {
                    this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
                }
                break;
            case socket_io_parser_1.PacketType.EVENT:
            case socket_io_parser_1.PacketType.BINARY_EVENT:
                this.onevent(packet);
                break;
            case socket_io_parser_1.PacketType.ACK:
            case socket_io_parser_1.PacketType.BINARY_ACK:
                this.onack(packet);
                break;
            case socket_io_parser_1.PacketType.DISCONNECT:
                this.ondisconnect();
                break;
            case socket_io_parser_1.PacketType.CONNECT_ERROR:
                this.destroy();
                const err = new Error(packet.data.message);
                // @ts-ignore
                err.data = packet.data.data;
                this.emitReserved("connect_error", err);
                break;
        }
    }
    /**
     * Called upon a server event.
     *
     * @param packet
     * @private
     */
    onevent(packet) {
        const args = packet.data || [];
        debug("emitting event %j", args);
        if (null != packet.id) {
            debug("attaching ack callback to event");
            args.push(this.ack(packet.id));
        }
        if (this.connected) {
            this.emitEvent(args);
        }
        else {
            this.receiveBuffer.push(Object.freeze(args));
        }
    }
    emitEvent(args) {
        if (this._anyListeners && this._anyListeners.length) {
            const listeners = this._anyListeners.slice();
            for (const listener of listeners) {
                listener.apply(this, args);
            }
        }
        super.emit.apply(this, args);
        if (this._pid && args.length && typeof args[args.length - 1] === "string") {
            this._lastOffset = args[args.length - 1];
        }
    }
    /**
     * Produces an ack callback to emit with an event.
     *
     * @private
     */
    ack(id) {
        const self = this;
        let sent = false;
        return function (...args) {
            // prevent double callbacks
            if (sent)
                return;
            sent = true;
            debug("sending ack %j", args);
            self.packet({
                type: socket_io_parser_1.PacketType.ACK,
                id: id,
                data: args,
            });
        };
    }
    /**
     * Called upon a server acknowledgement.
     *
     * @param packet
     * @private
     */
    onack(packet) {
        const ack = this.acks[packet.id];
        if (typeof ack !== "function") {
            debug("bad ack %s", packet.id);
            return;
        }
        delete this.acks[packet.id];
        debug("calling ack %s with %j", packet.id, packet.data);
        // @ts-ignore FIXME ack is incorrectly inferred as 'never'
        if (ack.withError) {
            packet.data.unshift(null);
        }
        // @ts-ignore
        ack.apply(this, packet.data);
    }
    /**
     * Called upon server connect.
     *
     * @private
     */
    onconnect(id, pid) {
        debug("socket connected with id %s", id);
        this.id = id;
        this.recovered = pid && this._pid === pid;
        this._pid = pid; // defined only if connection state recovery is enabled
        this.connected = true;
        this.emitBuffered();
        this.emitReserved("connect");
        this._drainQueue(true);
    }
    /**
     * Emit buffered events (received and emitted).
     *
     * @private
     */
    emitBuffered() {
        this.receiveBuffer.forEach((args) => this.emitEvent(args));
        this.receiveBuffer = [];
        this.sendBuffer.forEach((packet) => {
            this.notifyOutgoingListeners(packet);
            this.packet(packet);
        });
        this.sendBuffer = [];
    }
    /**
     * Called upon server disconnect.
     *
     * @private
     */
    ondisconnect() {
        debug("server disconnect (%s)", this.nsp);
        this.destroy();
        this.onclose("io server disconnect");
    }
    /**
     * Called upon forced client/server side disconnections,
     * this method ensures the manager stops tracking us and
     * that reconnections don't get triggered for this.
     *
     * @private
     */
    destroy() {
        if (this.subs) {
            // clean subscriptions to avoid reconnections
            this.subs.forEach((subDestroy) => subDestroy());
            this.subs = undefined;
        }
        this.io["_destroy"](this);
    }
    /**
     * Disconnects the socket manually. In that case, the socket will not try to reconnect.
     *
     * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
     *
     * @example
     * const socket = io();
     *
     * socket.on("disconnect", (reason) => {
     *   // console.log(reason); prints "io client disconnect"
     * });
     *
     * socket.disconnect();
     *
     * @return self
     */
    disconnect() {
        if (this.connected) {
            debug("performing disconnect (%s)", this.nsp);
            this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT });
        }
        // remove socket from pool
        this.destroy();
        if (this.connected) {
            // fire events
            this.onclose("io client disconnect");
        }
        return this;
    }
    /**
     * Alias for {@link disconnect()}.
     *
     * @return self
     */
    close() {
        return this.disconnect();
    }
    /**
     * Sets the compress flag.
     *
     * @example
     * socket.compress(false).emit("hello");
     *
     * @param compress - if `true`, compresses the sending data
     * @return self
     */
    compress(compress) {
        this.flags.compress = compress;
        return this;
    }
    /**
     * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
     * ready to send messages.
     *
     * @example
     * socket.volatile.emit("hello"); // the server may or may not receive it
     *
     * @returns self
     */
    get volatile() {
        this.flags.volatile = true;
        return this;
    }
    /**
     * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
     * given number of milliseconds have elapsed without an acknowledgement from the server:
     *
     * @example
     * socket.timeout(5000).emit("my-event", (err) => {
     *   if (err) {
     *     // the server did not acknowledge the event in the given delay
     *   }
     * });
     *
     * @returns self
     */
    timeout(timeout) {
        this.flags.timeout = timeout;
        return this;
    }
    /**
     * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
     * callback.
     *
     * @example
     * socket.onAny((event, ...args) => {
     *   console.log(`got ${event}`);
     * });
     *
     * @param listener
     */
    onAny(listener) {
        this._anyListeners = this._anyListeners || [];
        this._anyListeners.push(listener);
        return this;
    }
    /**
     * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
     * callback. The listener is added to the beginning of the listeners array.
     *
     * @example
     * socket.prependAny((event, ...args) => {
     *   console.log(`got event ${event}`);
     * });
     *
     * @param listener
     */
    prependAny(listener) {
        this._anyListeners = this._anyListeners || [];
        this._anyListeners.unshift(listener);
        return this;
    }
    /**
     * Removes the listener that will be fired when any event is emitted.
     *
     * @example
     * const catchAllListener = (event, ...args) => {
     *   console.log(`got event ${event}`);
     * }
     *
     * socket.onAny(catchAllListener);
     *
     * // remove a specific listener
     * socket.offAny(catchAllListener);
     *
     * // or remove all listeners
     * socket.offAny();
     *
     * @param listener
     */
    offAny(listener) {
        if (!this._anyListeners) {
            return this;
        }
        if (listener) {
            const listeners = this._anyListeners;
            for (let i = 0; i < listeners.length; i++) {
                if (listener === listeners[i]) {
                    listeners.splice(i, 1);
                    return this;
                }
            }
        }
        else {
            this._anyListeners = [];
        }
        return this;
    }
    /**
     * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
     * e.g. to remove listeners.
     */
    listenersAny() {
        return this._anyListeners || [];
    }
    /**
     * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
     * callback.
     *
     * Note: acknowledgements sent to the server are not included.
     *
     * @example
     * socket.onAnyOutgoing((event, ...args) => {
     *   console.log(`sent event ${event}`);
     * });
     *
     * @param listener
     */
    onAnyOutgoing(listener) {
        this._anyOutgoingListeners = this._anyOutgoingListeners || [];
        this._anyOutgoingListeners.push(listener);
        return this;
    }
    /**
     * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
     * callback. The listener is added to the beginning of the listeners array.
     *
     * Note: acknowledgements sent to the server are not included.
     *
     * @example
     * socket.prependAnyOutgoing((event, ...args) => {
     *   console.log(`sent event ${event}`);
     * });
     *
     * @param listener
     */
    prependAnyOutgoing(listener) {
        this._anyOutgoingListeners = this._anyOutgoingListeners || [];
        this._anyOutgoingListeners.unshift(listener);
        return this;
    }
    /**
     * Removes the listener that will be fired when any event is emitted.
     *
     * @example
     * const catchAllListener = (event, ...args) => {
     *   console.log(`sent event ${event}`);
     * }
     *
     * socket.onAnyOutgoing(catchAllListener);
     *
     * // remove a specific listener
     * socket.offAnyOutgoing(catchAllListener);
     *
     * // or remove all listeners
     * socket.offAnyOutgoing();
     *
     * @param [listener] - the catch-all listener (optional)
     */
    offAnyOutgoing(listener) {
        if (!this._anyOutgoingListeners) {
            return this;
        }
        if (listener) {
            const listeners = this._anyOutgoingListeners;
            for (let i = 0; i < listeners.length; i++) {
                if (listener === listeners[i]) {
                    listeners.splice(i, 1);
                    return this;
                }
            }
        }
        else {
            this._anyOutgoingListeners = [];
        }
        return this;
    }
    /**
     * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
     * e.g. to remove listeners.
     */
    listenersAnyOutgoing() {
        return this._anyOutgoingListeners || [];
    }
    /**
     * Notify the listeners for each packet sent
     *
     * @param packet
     *
     * @private
     */
    notifyOutgoingListeners(packet) {
        if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
            const listeners = this._anyOutgoingListeners.slice();
            for (const listener of listeners) {
                listener.apply(this, packet.data);
            }
        }
    }
}
exports.Socket = Socket;
 
},{"./on.js":33,"@socket.io/component-emitter":6,"debug":36,"socket.io-parser":39}],35:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.url = url;
const engine_io_client_1 = require("engine.io-client");
const debug_1 = __importDefault(require("debug")); // debug()
const debug = (0, debug_1.default)("socket.io-client:url"); // debug()
/**
 * URL parser.
 *
 * @param uri - url
 * @param path - the request path of the connection
 * @param loc - An object meant to mimic window.location.
 *        Defaults to window.location.
 * @public
 */
function url(uri, path = "", loc) {
    let obj = uri;
    // default to window.location
    loc = loc || (typeof location !== "undefined" && location);
    if (null == uri)
        uri = loc.protocol + "//" + loc.host;
    // relative path support
    if (typeof uri === "string") {
        if ("/" === uri.charAt(0)) {
            if ("/" === uri.charAt(1)) {
                uri = loc.protocol + uri;
            }
            else {
                uri = loc.host + uri;
            }
        }
        if (!/^(https?|wss?):\/\//.test(uri)) {
            debug("protocol-less url %s", uri);
            if ("undefined" !== typeof loc) {
                uri = loc.protocol + "//" + uri;
            }
            else {
                uri = "https://" + uri;
            }
        }
        // parse
        debug("parse %s", uri);
        obj = (0, engine_io_client_1.parse)(uri);
    }
    // make sure we treat `localhost:80` and `localhost` equally
    if (!obj.port) {
        if (/^(http|ws)$/.test(obj.protocol)) {
            obj.port = "80";
        }
        else if (/^(http|ws)s$/.test(obj.protocol)) {
            obj.port = "443";
        }
    }
    obj.path = obj.path || "/";
    const ipv6 = obj.host.indexOf(":") !== -1;
    const host = ipv6 ? "[" + obj.host + "]" : obj.host;
    // define unique id
    obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
    // define href
    obj.href =
        obj.protocol +
            "://" +
            host +
            (loc && loc.port === obj.port ? "" : ":" + obj.port);
    return obj;
}
 
},{"debug":36,"engine.io-client":11}],36:[function(require,module,exports){
arguments[4][21][0].apply(exports,arguments)
},{"./common":37,"_process":29,"dup":21}],37:[function(require,module,exports){
arguments[4][22][0].apply(exports,arguments)
},{"dup":22,"ms":28}],38:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reconstructPacket = exports.deconstructPacket = void 0;
const is_binary_js_1 = require("./is-binary.js");
/**
 * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
 *
 * @param {Object} packet - socket.io event packet
 * @return {Object} with deconstructed packet and list of buffers
 * @public
 */
function deconstructPacket(packet) {
    const buffers = [];
    const packetData = packet.data;
    const pack = packet;
    pack.data = _deconstructPacket(packetData, buffers);
    pack.attachments = buffers.length; // number of binary 'attachments'
    return { packet: pack, buffers: buffers };
}
exports.deconstructPacket = deconstructPacket;
function _deconstructPacket(data, buffers) {
    if (!data)
        return data;
    if ((0, is_binary_js_1.isBinary)(data)) {
        const placeholder = { _placeholder: true, num: buffers.length };
        buffers.push(data);
        return placeholder;
    }
    else if (Array.isArray(data)) {
        const newData = new Array(data.length);
        for (let i = 0; i < data.length; i++) {
            newData[i] = _deconstructPacket(data[i], buffers);
        }
        return newData;
    }
    else if (typeof data === "object" && !(data instanceof Date)) {
        const newData = {};
        for (const key in data) {
            if (Object.prototype.hasOwnProperty.call(data, key)) {
                newData[key] = _deconstructPacket(data[key], buffers);
            }
        }
        return newData;
    }
    return data;
}
/**
 * Reconstructs a binary packet from its placeholder packet and buffers
 *
 * @param {Object} packet - event packet with placeholders
 * @param {Array} buffers - binary buffers to put in placeholder positions
 * @return {Object} reconstructed packet
 * @public
 */
function reconstructPacket(packet, buffers) {
    packet.data = _reconstructPacket(packet.data, buffers);
    delete packet.attachments; // no longer useful
    return packet;
}
exports.reconstructPacket = reconstructPacket;
function _reconstructPacket(data, buffers) {
    if (!data)
        return data;
    if (data && data._placeholder === true) {
        const isIndexValid = typeof data.num === "number" &&
            data.num >= 0 &&
            data.num < buffers.length;
        if (isIndexValid) {
            return buffers[data.num]; // appropriate buffer (should be natural order anyway)
        }
        else {
            throw new Error("illegal attachments");
        }
    }
    else if (Array.isArray(data)) {
        for (let i = 0; i < data.length; i++) {
            data[i] = _reconstructPacket(data[i], buffers);
        }
    }
    else if (typeof data === "object") {
        for (const key in data) {
            if (Object.prototype.hasOwnProperty.call(data, key)) {
                data[key] = _reconstructPacket(data[key], buffers);
            }
        }
    }
    return data;
}
 
},{"./is-binary.js":40}],39:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Decoder = exports.Encoder = exports.PacketType = exports.protocol = void 0;
const component_emitter_1 = require("@socket.io/component-emitter");
const binary_js_1 = require("./binary.js");
const is_binary_js_1 = require("./is-binary.js");
const debug_1 = require("debug"); // debug()
const debug = (0, debug_1.default)("socket.io-parser"); // debug()
/**
 * These strings must not be used as event names, as they have a special meaning.
 */
const RESERVED_EVENTS = [
    "connect",
    "connect_error",
    "disconnect",
    "disconnecting",
    "newListener",
    "removeListener", // used by the Node.js EventEmitter
];
/**
 * Protocol version.
 *
 * @public
 */
exports.protocol = 5;
var PacketType;
(function (PacketType) {
    PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
    PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
    PacketType[PacketType["EVENT"] = 2] = "EVENT";
    PacketType[PacketType["ACK"] = 3] = "ACK";
    PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
    PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
    PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
})(PacketType = exports.PacketType || (exports.PacketType = {}));
/**
 * A socket.io Encoder instance
 */
class Encoder {
    /**
     * Encoder constructor
     *
     * @param {function} replacer - custom replacer to pass down to JSON.parse
     */
    constructor(replacer) {
        this.replacer = replacer;
    }
    /**
     * Encode a packet as a single string if non-binary, or as a
     * buffer sequence, depending on packet type.
     *
     * @param {Object} obj - packet object
     */
    encode(obj) {
        debug("encoding packet %j", obj);
        if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
            if ((0, is_binary_js_1.hasBinary)(obj)) {
                return this.encodeAsBinary({
                    type: obj.type === PacketType.EVENT
                        ? PacketType.BINARY_EVENT
                        : PacketType.BINARY_ACK,
                    nsp: obj.nsp,
                    data: obj.data,
                    id: obj.id,
                });
            }
        }
        return [this.encodeAsString(obj)];
    }
    /**
     * Encode packet as string.
     */
    encodeAsString(obj) {
        // first is type
        let str = "" + obj.type;
        // attachments if we have them
        if (obj.type === PacketType.BINARY_EVENT ||
            obj.type === PacketType.BINARY_ACK) {
            str += obj.attachments + "-";
        }
        // if we have a namespace other than `/`
        // we append it followed by a comma `,`
        if (obj.nsp && "/" !== obj.nsp) {
            str += obj.nsp + ",";
        }
        // immediately followed by the id
        if (null != obj.id) {
            str += obj.id;
        }
        // json data
        if (null != obj.data) {
            str += JSON.stringify(obj.data, this.replacer);
        }
        debug("encoded %j as %s", obj, str);
        return str;
    }
    /**
     * Encode packet as 'buffer sequence' by removing blobs, and
     * deconstructing packet into object with placeholders and
     * a list of buffers.
     */
    encodeAsBinary(obj) {
        const deconstruction = (0, binary_js_1.deconstructPacket)(obj);
        const pack = this.encodeAsString(deconstruction.packet);
        const buffers = deconstruction.buffers;
        buffers.unshift(pack); // add packet info to beginning of data list
        return buffers; // write all the buffers
    }
}
exports.Encoder = Encoder;
// see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
function isObject(value) {
    return Object.prototype.toString.call(value) === "[object Object]";
}
/**
 * A socket.io Decoder instance
 *
 * @return {Object} decoder
 */
class Decoder extends component_emitter_1.Emitter {
    /**
     * Decoder constructor
     *
     * @param {function} reviver - custom reviver to pass down to JSON.stringify
     */
    constructor(reviver) {
        super();
        this.reviver = reviver;
    }
    /**
     * Decodes an encoded packet string into packet JSON.
     *
     * @param {String} obj - encoded packet
     */
    add(obj) {
        let packet;
        if (typeof obj === "string") {
            if (this.reconstructor) {
                throw new Error("got plaintext data when reconstructing a packet");
            }
            packet = this.decodeString(obj);
            const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
            if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
                packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
                // binary packet's json
                this.reconstructor = new BinaryReconstructor(packet);
                // no attachments, labeled binary but no binary data to follow
                if (packet.attachments === 0) {
                    super.emitReserved("decoded", packet);
                }
            }
            else {
                // non-binary full packet
                super.emitReserved("decoded", packet);
            }
        }
        else if ((0, is_binary_js_1.isBinary)(obj) || obj.base64) {
            // raw binary data
            if (!this.reconstructor) {
                throw new Error("got binary data when not reconstructing a packet");
            }
            else {
                packet = this.reconstructor.takeBinaryData(obj);
                if (packet) {
                    // received final buffer
                    this.reconstructor = null;
                    super.emitReserved("decoded", packet);
                }
            }
        }
        else {
            throw new Error("Unknown type: " + obj);
        }
    }
    /**
     * Decode a packet String (JSON data)
     *
     * @param {String} str
     * @return {Object} packet
     */
    decodeString(str) {
        let i = 0;
        // look up type
        const p = {
            type: Number(str.charAt(0)),
        };
        if (PacketType[p.type] === undefined) {
            throw new Error("unknown packet type " + p.type);
        }
        // look up attachments if type binary
        if (p.type === PacketType.BINARY_EVENT ||
            p.type === PacketType.BINARY_ACK) {
            const start = i + 1;
            while (str.charAt(++i) !== "-" && i != str.length) { }
            const buf = str.substring(start, i);
            if (buf != Number(buf) || str.charAt(i) !== "-") {
                throw new Error("Illegal attachments");
            }
            p.attachments = Number(buf);
        }
        // look up namespace (if any)
        if ("/" === str.charAt(i + 1)) {
            const start = i + 1;
            while (++i) {
                const c = str.charAt(i);
                if ("," === c)
                    break;
                if (i === str.length)
                    break;
            }
            p.nsp = str.substring(start, i);
        }
        else {
            p.nsp = "/";
        }
        // look up id
        const next = str.charAt(i + 1);
        if ("" !== next && Number(next) == next) {
            const start = i + 1;
            while (++i) {
                const c = str.charAt(i);
                if (null == c || Number(c) != c) {
                    --i;
                    break;
                }
                if (i === str.length)
                    break;
            }
            p.id = Number(str.substring(start, i + 1));
        }
        // look up json data
        if (str.charAt(++i)) {
            const payload = this.tryParse(str.substr(i));
            if (Decoder.isPayloadValid(p.type, payload)) {
                p.data = payload;
            }
            else {
                throw new Error("invalid payload");
            }
        }
        debug("decoded %s as %j", str, p);
        return p;
    }
    tryParse(str) {
        try {
            return JSON.parse(str, this.reviver);
        }
        catch (e) {
            return false;
        }
    }
    static isPayloadValid(type, payload) {
        switch (type) {
            case PacketType.CONNECT:
                return isObject(payload);
            case PacketType.DISCONNECT:
                return payload === undefined;
            case PacketType.CONNECT_ERROR:
                return typeof payload === "string" || isObject(payload);
            case PacketType.EVENT:
            case PacketType.BINARY_EVENT:
                return (Array.isArray(payload) &&
                    (typeof payload[0] === "number" ||
                        (typeof payload[0] === "string" &&
                            RESERVED_EVENTS.indexOf(payload[0]) === -1)));
            case PacketType.ACK:
            case PacketType.BINARY_ACK:
                return Array.isArray(payload);
        }
    }
    /**
     * Deallocates a parser's resources
     */
    destroy() {
        if (this.reconstructor) {
            this.reconstructor.finishedReconstruction();
            this.reconstructor = null;
        }
    }
}
exports.Decoder = Decoder;
/**
 * A manager of a binary event's 'buffer sequence'. Should
 * be constructed whenever a packet of type BINARY_EVENT is
 * decoded.
 *
 * @param {Object} packet
 * @return {BinaryReconstructor} initialized reconstructor
 */
class BinaryReconstructor {
    constructor(packet) {
        this.packet = packet;
        this.buffers = [];
        this.reconPack = packet;
    }
    /**
     * Method to be called when binary data received from connection
     * after a BINARY_EVENT packet.
     *
     * @param {Buffer | ArrayBuffer} binData - the raw binary data received
     * @return {null | Object} returns null if more binary data is expected or
     *   a reconstructed packet object if all buffers have been received.
     */
    takeBinaryData(binData) {
        this.buffers.push(binData);
        if (this.buffers.length === this.reconPack.attachments) {
            // done with buffer list
            const packet = (0, binary_js_1.reconstructPacket)(this.reconPack, this.buffers);
            this.finishedReconstruction();
            return packet;
        }
        return null;
    }
    /**
     * Cleans up binary packet reconstruction variables.
     */
    finishedReconstruction() {
        this.reconPack = null;
        this.buffers = [];
    }
}
 
},{"./binary.js":38,"./is-binary.js":40,"@socket.io/component-emitter":6,"debug":41}],40:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasBinary = exports.isBinary = void 0;
const withNativeArrayBuffer = typeof ArrayBuffer === "function";
const isView = (obj) => {
    return typeof ArrayBuffer.isView === "function"
        ? ArrayBuffer.isView(obj)
        : obj.buffer instanceof ArrayBuffer;
};
const toString = Object.prototype.toString;
const withNativeBlob = typeof Blob === "function" ||
    (typeof Blob !== "undefined" &&
        toString.call(Blob) === "[object BlobConstructor]");
const withNativeFile = typeof File === "function" ||
    (typeof File !== "undefined" &&
        toString.call(File) === "[object FileConstructor]");
/**
 * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
 *
 * @private
 */
function isBinary(obj) {
    return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
        (withNativeBlob && obj instanceof Blob) ||
        (withNativeFile && obj instanceof File));
}
exports.isBinary = isBinary;
function hasBinary(obj, toJSON) {
    if (!obj || typeof obj !== "object") {
        return false;
    }
    if (Array.isArray(obj)) {
        for (let i = 0, l = obj.length; i < l; i++) {
            if (hasBinary(obj[i])) {
                return true;
            }
        }
        return false;
    }
    if (isBinary(obj)) {
        return true;
    }
    if (obj.toJSON &&
        typeof obj.toJSON === "function" &&
        arguments.length === 1) {
        return hasBinary(obj.toJSON(), true);
    }
    for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
            return true;
        }
    }
    return false;
}
exports.hasBinary = hasBinary;
 
},{}],41:[function(require,module,exports){
arguments[4][21][0].apply(exports,arguments)
},{"./common":42,"_process":29,"dup":21}],42:[function(require,module,exports){
arguments[4][22][0].apply(exports,arguments)
},{"dup":22,"ms":28}],43:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createCircularProgress = createCircularProgress;
/**
 * Circular Progress Spinner Component
 * Usage: createCircularProgress({ value, label, state, id })
 * - value: 0-100 (percent)
 * - label: status message (optional)
 * - state: '', 'error', 'warning', 'complete', 'ready' (optional)
 * - id: DOM id (optional)
 * 
 * Fixes visual duplication and rendering bugs in progress spinner during async operations
 */
function createCircularProgress() {
  let {
    value = 0,
    label = '',
    state = '',
    id = ''
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  // Ensure proper sizing and rendering calculations
  const size = 80;
  const stroke = 8;
  const radius = (size - stroke) / 2;
  const circumference = 2 * Math.PI * radius;
 
  // Clamp value between 0 and 100
  const percent = Math.max(0, Math.min(100, value));
 
  // Calculate stroke dash array for proper circular progress
  const dashOffset = circumference - percent / 100 * circumference;
 
  // Generate unique ID if not provided
  const elementId = id || `circular-progress-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
 
  // Create wrapper element with proper state management
  const wrapper = document.createElement('div');
  wrapper.className = `circular-progress${state ? ' ' + state : ''}`;
  wrapper.id = elementId;
  wrapper.setAttribute('role', 'progressbar');
  wrapper.setAttribute('aria-valuenow', percent);
  wrapper.setAttribute('aria-valuemin', 0);
  wrapper.setAttribute('aria-valuemax', 100);
  wrapper.setAttribute('aria-label', label ? `${label} ${percent}%` : `${percent}%`);
 
  // Add data attributes for debugging and state tracking
  wrapper.setAttribute('data-percent', percent);
  wrapper.setAttribute('data-state', state);
  wrapper.setAttribute('data-created', new Date().toISOString());
 
  // Create SVG with proper viewBox and dimensions
  wrapper.innerHTML = `
    <svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
      <!-- Background circle -->
      <circle 
        class="circular-bg" 
        cx="${size / 2}" 
        cy="${size / 2}" 
        r="${radius}" 
        fill="none"
        stroke="#e0e0e0"
        stroke-width="${stroke}"
      />
      <!-- Foreground progress circle -->
      <circle 
        class="circular-fg" 
        cx="${size / 2}" 
        cy="${size / 2}" 
        r="${radius}" 
        fill="none"
        stroke="var(--brand-color, #7c3aed)"
        stroke-width="${stroke}"
        stroke-linecap="round"
        stroke-dasharray="${circumference}"
        stroke-dashoffset="${dashOffset}"
        transform="rotate(-90 ${size / 2} ${size / 2})"
      />
    </svg>
    <!-- Percentage label -->
    <span class="circular-label">${Math.round(percent)}%</span>
    ${label ? `<span class="circular-status">${label}</span>` : ''}
  `;
 
  // Add debug logging for spinner creation
  console.debug('Circular Progress Created:', {
    id: elementId,
    percent,
    state,
    size,
    stroke,
    radius,
    circumference,
    dashOffset,
    label
  });
  return wrapper;
}
 
},{}],44:[function(require,module,exports){
"use strict";
 
/**
 * Credentials Modal Module
 * Shows current PingOne credentials and asks user if they want to use them or configure new ones
 */
class CredentialsModal {
  constructor() {
    this.isActive = false;
    this.focusableElements = [];
    this.firstFocusableElement = null;
    this.lastFocusableElement = null;
    this.previousActiveElement = null;
    this.credentials = null;
    this.init();
  }
  async init() {
    await this.loadCredentials();
    this.createModal();
    this.bindEvents();
    this.showModal();
  }
  async loadCredentials() {
    try {
      const response = await fetch('/api/settings');
      if (response.ok) {
        const data = await response.json();
        // The API returns data in data.data structure
        const settings = data.data || data.settings || {};
        this.credentials = {
          environmentId: settings.environmentId || settings['environment-id'] || '',
          clientId: settings.apiClientId || settings['api-client-id'] || '',
          clientSecret: settings.apiSecret || settings['api-secret'] || '',
          region: settings.region || 'NorthAmerica',
          populationId: settings.populationId || settings['population-id'] || '',
          rateLimit: settings.rateLimit || settings['rate-limit'] || 90
        };
        console.log('Credentials loaded from server:', {
          hasEnvironmentId: !!this.credentials.environmentId,
          hasClientId: !!this.credentials.clientId,
          hasClientSecret: !!this.credentials.clientSecret,
          region: this.credentials.region
        });
      } else {
        console.warn('Failed to load credentials from settings');
        this.credentials = null;
      }
    } catch (error) {
      console.error('Error loading credentials:', error);
      this.credentials = null;
    }
  }
  createModal() {
    // Create modal overlay
    const overlay = document.createElement('div');
    overlay.className = 'credentials-modal-overlay';
    overlay.setAttribute('role', 'dialog');
    overlay.setAttribute('aria-modal', 'true');
    overlay.setAttribute('aria-labelledby', 'credentials-title');
    overlay.setAttribute('aria-describedby', 'credentials-content');
    const hasCredentials = this.credentials && this.credentials.environmentId && this.credentials.clientId;
 
    // Create modal content
    overlay.innerHTML = `
            <div class="credentials-modal" tabindex="-1">
                <div class="credentials-modal-header">
                    <h2 id="credentials-title">
                        <span class="credentials-icon" aria-hidden="true">🔐</span>
                        <span>PingOne Credentials</span>
                    </h2>
                </div>
                
                <div class="credentials-modal-body">
                    <div id="credentials-content" class="credentials-content">
                        ${hasCredentials ? this.createCredentialsContent() : this.createNoCredentialsContent()}
                    </div>
                </div>
                
                <div class="credentials-modal-footer">
                    <div class="credentials-actions">
                        ${hasCredentials ? this.createCredentialsActions() : this.createNoCredentialsActions()}
                    </div>
                </div>
            </div>
        `;
    document.body.appendChild(overlay);
    this.overlay = overlay;
    this.modal = overlay.querySelector('.credentials-modal');
    this.useCredentialsBtn = overlay.querySelector('#use-credentials-btn');
    this.configureBtn = overlay.querySelector('#configure-credentials-btn');
    this.skipBtn = overlay.querySelector('#skip-credentials-btn');
  }
  createCredentialsContent() {
    return `
            <h3>🔐 PingOne Credentials Found</h3>
            <p>The following PingOne credentials are available. Would you like to use them or configure new ones?</p>
            
            <div class="credentials-display">
                <div class="credential-item">
                    <label>Environment ID:</label>
                    <div class="credential-value">
                        <code class="credential-visible">${this.credentials.environmentId}</code>
                        <button class="btn btn-sm btn-outline-secondary copy-btn" data-value="${this.credentials.environmentId}" title="Copy Environment ID">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
                
                <div class="credential-item">
                    <label>Client ID:</label>
                    <div class="credential-value">
                        <code class="credential-visible">${this.credentials.clientId}</code>
                        <button class="btn btn-sm btn-outline-secondary copy-btn" data-value="${this.credentials.clientId}" title="Copy Client ID">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
                
                <div class="credential-item">
                    <label>Client Secret:</label>
                    <div class="credential-value">
                        <code class="credential-masked">${this.credentials.clientSecret ? this.credentials.clientSecret.substring(0, 5) + '•'.repeat(Math.max(0, 15)) : '••••••••••••••••••••'}</code>
                        <span class="credential-status">✅ Configured</span>
                    </div>
                </div>
                
                <div class="credential-item">
                    <label>Region:</label>
                    <div class="credential-value">
                        <code class="credential-visible">${this.credentials.region}</code>
                    </div>
                </div>
            </div>
            
            <div class="credentials-info">
                <h4>💡 What would you like to do?</h4>
                <ul>
                    <li><strong>Use These Credentials:</strong> Continue with the stored credentials</li>
                    <li><strong>Go to Settings:</strong> Configure new or different credentials</li>
                </ul>
            </div>
        `;
  }
  createNoCredentialsContent() {
    return `
            <h3>🔧 No Credentials Found</h3>
            <p>No PingOne credentials were found in your settings. You'll need to configure them to use this tool.</p>
            
            <div class="credentials-info">
                <h4>📋 Required Information:</h4>
                <ul>
                    <li><strong>Environment ID:</strong> Your PingOne environment identifier</li>
                    <li><strong>Client ID:</strong> Your PingOne API client identifier</li>
                    <li><strong>Client Secret:</strong> Your PingOne API client secret</li>
                    <li><strong>Region:</strong> Your PingOne environment region</li>
                </ul>
            </div>
            
            <div class="credentials-help">
                <h4>💡 How to Get Credentials:</h4>
                <ol>
                    <li>Log into your PingOne Admin Console</li>
                    <li>Navigate to Applications → Applications</li>
                    <li>Create a new application or use an existing one</li>
                    <li>Copy the Environment ID, Client ID, and Client Secret</li>
                    <li>Configure them in the Settings page</li>
                </ol>
            </div>
        `;
  }
  createCredentialsActions() {
    return `
            <button type="button" class="credentials-btn credentials-btn-primary" id="use-credentials-btn">
                <i class="fas fa-play"></i>
                Use These Credentials
            </button>
            <button type="button" class="credentials-btn credentials-btn-secondary" id="configure-credentials-btn">
                <i class="fas fa-cog"></i>
                Go to Settings
            </button>
            <button type="button" class="credentials-btn credentials-btn-outline" id="skip-credentials-btn">
                <i class="fas fa-times"></i>
                Skip for Now
            </button>
        `;
  }
  createNoCredentialsActions() {
    return `
            <button type="button" class="credentials-btn credentials-btn-primary" id="configure-credentials-btn">
                <i class="fas fa-cog"></i>
                Go to Settings
            </button>
            <button type="button" class="credentials-btn credentials-btn-secondary" id="skip-credentials-btn">
                <i class="fas fa-times"></i>
                Skip for Now
            </button>
        `;
  }
  maskCredential(value) {
    if (!value) return 'Not set';
    if (value.length <= 8) return value;
    return value.substring(0, 8) + '...' + value.substring(value.length - 4);
  }
  bindEvents() {
    // Use credentials button
    if (this.useCredentialsBtn) {
      this.useCredentialsBtn.addEventListener('click', async () => {
        await this.useCurrentCredentials();
      });
    }
 
    // Configure credentials button
    if (this.configureBtn) {
      this.configureBtn.addEventListener('click', () => {
        this.goToSettings();
      });
    }
 
    // Skip button
    if (this.skipBtn) {
      this.skipBtn.addEventListener('click', () => {
        this.skipCredentials();
      });
    }
 
    // Copy buttons
    this.modal.querySelectorAll('.copy-btn').forEach(btn => {
      btn.addEventListener('click', e => {
        const value = e.target.closest('.copy-btn').dataset.value;
        this.copyToClipboard(value, e.target.closest('.copy-btn'));
      });
    });
 
    // Keyboard events for accessibility
    this.overlay.addEventListener('keydown', e => {
      this.handleKeyboardNavigation(e);
    });
 
    // Prevent clicks outside modal from closing it
    this.overlay.addEventListener('click', e => {
      if (e.target === this.overlay) {
        // Don't close on outside click - require explicit action
        this.logEvent('credentials_outside_click_prevented');
      }
    });
 
    // Escape key handling
    document.addEventListener('keydown', e => {
      if (e.key === 'Escape' && this.isActive) {
        e.preventDefault();
        this.skipCredentials();
      }
    });
  }
  handleKeyboardNavigation(e) {
    if (!this.isActive) return;
    const focusableElements = this.getFocusableElements();
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];
 
    // Tab key navigation with focus trapping
    if (e.key === 'Tab') {
      if (e.shiftKey) {
        if (document.activeElement === firstElement) {
          e.preventDefault();
          lastElement.focus();
        }
      } else {
        if (document.activeElement === lastElement) {
          e.preventDefault();
          firstElement.focus();
        }
      }
    }
  }
  getFocusableElements() {
    const focusableSelectors = ['button:not([disabled])', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'a[href]', '[tabindex]:not([tabindex="-1"])'];
    return Array.from(this.modal.querySelectorAll(focusableSelectors.join(', ')));
  }
  showModal() {
    this.isActive = true;
    this.previousActiveElement = document.activeElement;
 
    // Add classes to body and app container
    document.body.classList.add('credentials-modal-open');
    const appContainer = document.querySelector('.app-container');
    if (appContainer) {
      appContainer.classList.add('credentials-modal-active');
    }
 
    // Show modal with animation
    this.overlay.classList.add('active');
 
    // Focus management
    this.modal.focus();
    this.setupFocusTrap();
    this.logEvent('credentials_modal_shown');
 
    // Announce to screen readers
    this.announceToScreenReader('Credentials configuration modal opened. Please review your PingOne credentials and choose an action.');
  }
  setupFocusTrap() {
    this.focusableElements = this.getFocusableElements();
    this.firstFocusableElement = this.focusableElements[0];
    this.lastFocusableElement = this.focusableElements[this.focusableElements.length - 1];
  }
  async useCurrentCredentials() {
    this.logEvent('credentials_used', {
      hasCredentials: !!this.credentials,
      environmentId: this.credentials?.environmentId ? 'set' : 'not_set',
      clientId: this.credentials?.clientId ? 'set' : 'not_set'
    });
 
    // Show loading state on button
    const useButton = document.getElementById('use-credentials-btn');
    if (useButton) {
      useButton.disabled = true;
      useButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Validating Credentials...';
    }
    try {
      // Just save credentials without trying to get a token
      await this.saveCredentialsOnly();
 
      // Mark modal as shown since credentials are now saved
      CredentialsModal.setCredentialsModalShown();
      this.hideModal();
      this.enableApplication();
 
      // Update token status to reflect that credentials are now being used
      this.updateTokenStatusAfterCredentialsUse();
 
      // Show success message
      this.showSuccessMessage('Credentials saved successfully!');
    } catch (error) {
      // Restore button state on error
      const useButton = document.getElementById('use-credentials-btn');
      if (useButton) {
        useButton.disabled = false;
        useButton.innerHTML = '<i class="fas fa-play"></i> Use These Credentials';
      }
      console.error('Error using credentials:', error);
 
      // Show user-friendly error messages
      let userMessage = '';
      let userTitle = 'Credentials Error';
      if (error.message.includes('PingOne client not available')) {
        userTitle = 'Authentication System Not Ready';
        userMessage = 'The PingOne authentication system is not fully initialized. Please refresh the page and try again, or go to Settings to configure credentials manually.';
      } else if (error.message.includes('Missing required credentials')) {
        userTitle = 'Incomplete Credentials';
        userMessage = 'Some required credential fields are missing. Please go to Settings to complete your PingOne configuration.';
      } else if (error.message.includes('Failed to get token')) {
        userTitle = 'Authentication Failed';
        userMessage = 'Unable to authenticate with PingOne using these credentials. Please verify your credentials in Settings.';
      } else if (error.message.includes('Failed to save credentials')) {
        userTitle = 'Save Failed';
        userMessage = 'Unable to save credentials to the server. Please try again or go to Settings to configure manually.';
      } else {
        userTitle = 'Credentials Error';
        userMessage = 'There was a problem using these credentials. Please go to Settings to verify your PingOne configuration.';
      }
 
      // Show the user-friendly error in the modal
      this.showModalError(userTitle, userMessage);
    }
  }
  async saveCredentialsAndGetToken() {
    if (!this.credentials) {
      throw new Error('No credentials available to save');
    }
 
    // Convert credentials to settings format
    const settings = {
      environmentId: this.credentials.environmentId,
      apiClientId: this.credentials.clientId,
      apiSecret: this.credentials.clientSecret,
      populationId: this.credentials.populationId || '',
      region: this.credentials.region || 'NorthAmerica',
      rateLimit: this.credentials.rateLimit || 90
    };
 
    // Validate required fields before saving
    if (!settings.environmentId || !settings.apiClientId || !settings.apiSecret) {
      throw new Error('Missing required credentials: Environment ID, Client ID, and Client Secret are required');
    }
 
    // Save to server via API endpoint - this is the critical fix
    try {
      console.log('Saving credentials to server...', {
        hasEnvironmentId: !!settings.environmentId,
        hasApiClientId: !!settings.apiClientId,
        hasApiSecret: !!settings.apiSecret,
        region: settings.region
      });
      const response = await fetch('/api/settings', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(settings)
      });
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(`Failed to save credentials to server: ${errorData.error || response.statusText}`);
      }
      const result = await response.json();
      console.log('Credentials saved to server successfully:', result);
 
      // Verify the save was successful by reading back the settings
      const verifyResponse = await fetch('/api/settings');
      if (verifyResponse.ok) {
        const verifyData = await verifyResponse.json();
        const savedSettings = verifyData.data || verifyData.settings || {};
        console.log('Verified credentials saved to server:', {
          hasEnvironmentId: !!savedSettings.environmentId,
          hasApiClientId: !!savedSettings.apiClientId,
          hasApiSecret: !!savedSettings.apiSecret
        });
      }
    } catch (error) {
      console.error('Failed to save credentials to server:', error);
      throw new Error(`Failed to save credentials: ${error.message}`);
    }
 
    // Save to credentials manager if available
    if (window.credentialsManager) {
      try {
        window.credentialsManager.saveCredentials(settings);
        console.log('Credentials saved to credentials manager');
      } catch (error) {
        console.warn('Failed to save to credentials manager:', error);
      }
    }
 
    // Save to localStorage as backup
    try {
      localStorage.setItem('pingone_credentials', JSON.stringify(settings));
      console.log('Credentials saved to localStorage as backup');
    } catch (error) {
      console.warn('Failed to save to localStorage:', error);
    }
 
    // Update settings form if on settings page
    if (window.app && window.app.populateSettingsForm) {
      try {
        window.app.populateSettingsForm(settings);
        console.log('Settings form updated with credentials');
      } catch (error) {
        console.warn('Failed to update settings form:', error);
      }
    }
 
    // Get a new token with the saved credentials - with retry logic
    let tokenResult = null;
    let lastError = null;
 
    // Wait a moment for credentials to be processed by the server
    await new Promise(resolve => setTimeout(resolve, 1000));
 
    // Try multiple approaches to get a token
    for (let attempt = 1; attempt <= 3; attempt++) {
      console.log(`Token acquisition attempt ${attempt}/3`);
 
      // First try: Direct API call (most reliable)
      try {
        console.log('Trying direct API call approach...');
        const response = await fetch('/api/pingone/token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        if (response.ok) {
          const tokenData = await response.json();
          if (tokenData.access_token) {
            console.log('Token acquired via direct API call');
            tokenResult = tokenData.access_token;
            break; // Success!
          }
        } else {
          const errorData = await response.json().catch(() => ({}));
          lastError = new Error(errorData.error || 'Failed to get token from API');
          console.error(`Direct API approach failed (attempt ${attempt}):`, lastError.message);
        }
      } catch (apiError) {
        console.error(`Direct API approach failed (attempt ${attempt}):`, apiError);
        lastError = apiError;
      }
 
      // Second try: Use PingOne client if available (fallback)
      if (!tokenResult && window.app && window.app.pingOneClient) {
        try {
          console.log('Trying PingOne client approach as fallback...');
          // Update the PingOne client with new credentials
          if (typeof window.app.pingOneClient.updateCredentials === 'function') {
            window.app.pingOneClient.updateCredentials(settings);
          }
 
          // Get a new token
          const token = await window.app.pingOneClient.getAccessToken();
          console.log('New token acquired with saved credentials via PingOne client');
          tokenResult = token;
          break; // Success!
        } catch (error) {
          console.error(`PingOne client approach failed (attempt ${attempt}):`, error);
          lastError = error;
        }
      } else if (!tokenResult) {
        console.log('PingOne client not available, skipping client approach');
      }
 
      // Third try: Enhanced server auth endpoint
      if (!tokenResult) {
        try {
          console.log('Trying enhanced server auth approach...');
          const response = await fetch('/api/v1/auth/token', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              environmentId: settings.environmentId,
              clientId: settings.apiClientId,
              clientSecret: settings.apiSecret,
              region: settings.region
            })
          });
          if (response.ok) {
            const tokenData = await response.json();
            if (tokenData.access_token || tokenData.token) {
              console.log('Token acquired via enhanced server auth');
              tokenResult = tokenData.access_token || tokenData.token;
              break; // Success!
            }
          } else {
            const errorData = await response.json().catch(() => ({}));
            lastError = new Error(errorData.error || 'Failed to get token from enhanced auth');
            console.error(`Enhanced server auth approach failed (attempt ${attempt}):`, lastError.message);
          }
        } catch (authError) {
          console.error(`Enhanced server auth approach failed (attempt ${attempt}):`, authError);
          lastError = authError;
        }
      }
 
      // Wait before retry (exponential backoff)
      if (attempt < 3 && !tokenResult) {
        const waitTime = 1000 * attempt;
        console.log(`Waiting ${waitTime}ms before retry...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
      }
    }
 
    // Check if we got a token
    if (!tokenResult) {
      console.error('All token acquisition attempts failed');
 
      // Provide helpful error message based on the last error
      let errorMessage = 'Unable to acquire PingOne access token after multiple attempts.';
      if (lastError) {
        if (lastError.message.includes('401') || lastError.message.includes('unauthorized')) {
          errorMessage = 'Invalid credentials. Please verify your PingOne Client ID and Secret are correct.';
        } else if (lastError.message.includes('404') || lastError.message.includes('not found')) {
          errorMessage = 'PingOne environment not found. Please verify your Environment ID is correct.';
        } else if (lastError.message.includes('network') || lastError.message.includes('fetch')) {
          errorMessage = 'Network error connecting to PingOne. Please check your internet connection.';
        } else if (lastError.message.includes('PingOne client not available')) {
          errorMessage = 'PingOne authentication system is not properly initialized. Please refresh the page and try again.';
        } else {
          errorMessage = `Authentication failed: ${lastError.message}`;
        }
      }
      throw new Error(errorMessage);
    }
    console.log('Token acquisition successful');
    return tokenResult;
  }
  async saveCredentialsOnly() {
    if (!this.credentials) {
      throw new Error('No credentials available to save');
    }
 
    // Convert credentials to settings format
    const settings = {
      environmentId: this.credentials.environmentId,
      apiClientId: this.credentials.clientId,
      apiSecret: this.credentials.clientSecret,
      populationId: this.credentials.populationId || '',
      region: this.credentials.region || 'NorthAmerica',
      rateLimit: this.credentials.rateLimit || 90
    };
 
    // Validate required fields before saving
    if (!settings.environmentId || !settings.apiClientId || !settings.apiSecret) {
      throw new Error('Missing required credentials: Environment ID, Client ID, and Client Secret are required');
    }
 
    // Save to server via API endpoint
    try {
      console.log('Saving credentials to server...', {
        hasEnvironmentId: !!settings.environmentId,
        hasApiClientId: !!settings.apiClientId,
        hasApiSecret: !!settings.apiSecret,
        region: settings.region
      });
      const response = await fetch('/api/settings', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(settings)
      });
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(`Failed to save credentials to server: ${errorData.error || response.statusText}`);
      }
      const result = await response.json();
      console.log('Credentials saved to server successfully:', result);
    } catch (error) {
      console.error('Failed to save credentials to server:', error);
      throw new Error(`Failed to save credentials: ${error.message}`);
    }
 
    // Save to credentials manager if available
    if (window.credentialsManager) {
      try {
        window.credentialsManager.saveCredentials(settings);
        console.log('Credentials saved to credentials manager');
      } catch (error) {
        console.warn('Failed to save to credentials manager:', error);
      }
    }
 
    // Save to localStorage as backup
    try {
      localStorage.setItem('pingone_credentials', JSON.stringify(settings));
      console.log('Credentials saved to localStorage as backup');
    } catch (error) {
      console.warn('Failed to save to localStorage:', error);
    }
 
    // Update settings form if on settings page
    if (window.app && window.app.populateSettingsForm) {
      try {
        window.app.populateSettingsForm(settings);
        console.log('Settings form updated with credentials');
      } catch (error) {
        console.warn('Failed to update settings form:', error);
      }
    }
    console.log('Credentials saved successfully without token acquisition');
    return true;
  }
  showError(title, message) {
    // Create and show an error notification
    const notification = document.createElement('div');
    notification.className = 'notification notification-error';
    notification.innerHTML = `
            <i class="fas fa-exclamation-circle"></i>
            <span><strong>${title}:</strong> ${message}</span>
        `;
    const notificationArea = document.getElementById('notification-area');
    if (notificationArea) {
      notificationArea.appendChild(notification);
      setTimeout(() => {
        notification.remove();
      }, 8000);
    }
  }
  showModalError(title, message) {
    // Show error directly in the modal
    const modal = document.querySelector('.credentials-modal');
    if (!modal) return;
 
    // Remove any existing error messages
    const existingError = modal.querySelector('.credentials-error-message');
    if (existingError) {
      existingError.remove();
    }
 
    // Create error message element
    const errorDiv = document.createElement('div');
    errorDiv.className = 'credentials-error-message';
    errorDiv.innerHTML = `
            <div class="error-content">
                <i class="fas fa-exclamation-triangle error-icon"></i>
                <div class="error-text">
                    <h4>${title}</h4>
                    <p>${message}</p>
                </div>
            </div>
            <div class="error-actions">
                <button type="button" class="btn btn-primary" onclick="this.closest('.credentials-modal-overlay').querySelector('#configure-credentials-btn').click()">
                    <i class="fas fa-cog"></i> Go to Settings
                </button>
                <button type="button" class="btn btn-secondary" onclick="this.closest('.credentials-error-message').remove()">
                    <i class="fas fa-times"></i> Dismiss
                </button>
            </div>
        `;
 
    // Insert error message after the modal body
    const modalBody = modal.querySelector('.credentials-modal-body');
    if (modalBody) {
      modalBody.insertAdjacentElement('afterend', errorDiv);
    }
 
    // Also call the regular showError for notifications
    this.showError(title, message);
  }
  updateTokenStatusAfterCredentialsUse() {
    try {
      console.log('Credentials Modal: Updating token status after credentials use');
 
      // Force a token refresh to get current status
      if (window.app && window.app.pingOneClient) {
        // Clear any existing token to force refresh
        window.app.pingOneClient.clearToken();
 
        // Get a fresh token
        window.app.pingOneClient.getAccessToken().then(token => {
          console.log('Credentials Modal: Fresh token acquired');
 
          // Update the universal token status
          if (typeof window.app.updateUniversalTokenStatus === 'function') {
            window.app.updateUniversalTokenStatus();
          }
        }).catch(error => {
          console.warn('Credentials Modal: Could not get fresh token:', error);
        });
      }
 
      // Also try to update status directly
      if (window.app && typeof window.app.updateUniversalTokenStatus === 'function') {
        setTimeout(() => {
          window.app.updateUniversalTokenStatus();
        }, 1000);
      }
    } catch (error) {
      console.error('Credentials Modal: Error updating token status:', error);
    }
  }
  goToSettings() {
    this.logEvent('credentials_configure_clicked');
    this.hideModal();
    this.enableApplication();
 
    // Navigate to settings
    setTimeout(() => {
      const settingsNav = document.querySelector('[data-view="settings"]');
      if (settingsNav) {
        settingsNav.click();
      }
    }, 100);
  }
  skipCredentials() {
    this.logEvent('credentials_skipped');
    this.hideModal();
    this.enableApplication();
 
    // Show info message
    this.showInfoMessage('You can configure credentials later in the Settings page.');
  }
  hideModal() {
    this.isActive = false;
 
    // Remove classes
    document.body.classList.remove('credentials-modal-open');
    const appContainer = document.querySelector('.app-container');
    if (appContainer) {
      appContainer.classList.remove('credentials-modal-active');
    }
 
    // Hide modal with animation
    this.overlay.classList.remove('active');
 
    // Restore focus
    if (this.previousActiveElement) {
      this.previousActiveElement.focus();
    }
 
    // Clean up
    setTimeout(() => {
      if (this.overlay && this.overlay.parentNode) {
        this.overlay.parentNode.removeChild(this.overlay);
      }
    }, 300);
    this.logEvent('credentials_modal_hidden');
  }
  enableApplication() {
    // Enable the application
    const appContainer = document.querySelector('.app-container');
    if (appContainer) {
      appContainer.classList.remove('credentials-modal-active');
    }
    this.logEvent('application_enabled_after_credentials');
  }
  copyToClipboard(text, button) {
    navigator.clipboard.writeText(text).then(() => {
      // Show success feedback
      const originalIcon = button.innerHTML;
      button.innerHTML = '<i class="fas fa-check"></i>';
      button.classList.add('copied');
      setTimeout(() => {
        button.innerHTML = originalIcon;
        button.classList.remove('copied');
      }, 2000);
      this.logEvent('credential_copied');
    }).catch(err => {
      console.error('Failed to copy to clipboard:', err);
      this.logEvent('credential_copy_failed', {
        error: err.message
      });
    });
  }
  showSuccessMessage(message) {
    // Create and show a success notification
    const notification = document.createElement('div');
    notification.className = 'notification notification-success';
    notification.innerHTML = `
            <i class="fas fa-check-circle"></i>
            <span>${message}</span>
        `;
    const notificationArea = document.getElementById('notification-area');
    if (notificationArea) {
      notificationArea.appendChild(notification);
      setTimeout(() => {
        notification.remove();
      }, 5000);
    }
  }
  showInfoMessage(message) {
    // Create and show an info notification
    const notification = document.createElement('div');
    notification.className = 'notification notification-info';
    notification.innerHTML = `
            <i class="fas fa-info-circle"></i>
            <span>${message}</span>
        `;
    const notificationArea = document.getElementById('notification-area');
    if (notificationArea) {
      notificationArea.appendChild(notification);
      setTimeout(() => {
        notification.remove();
      }, 5000);
    }
  }
  announceToScreenReader(message) {
    // Create a temporary element for screen reader announcements
    const announcement = document.createElement('div');
    announcement.setAttribute('aria-live', 'polite');
    announcement.setAttribute('aria-atomic', 'true');
    announcement.style.position = 'absolute';
    announcement.style.left = '-10000px';
    announcement.style.width = '1px';
    announcement.style.height = '1px';
    announcement.style.overflow = 'hidden';
    announcement.textContent = message;
    document.body.appendChild(announcement);
    setTimeout(() => {
      document.body.removeChild(announcement);
    }, 1000);
  }
  logEvent(eventName) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    const eventData = {
      event: eventName,
      timestamp: new Date().toISOString(),
      hasCredentials: !!this.credentials,
      environmentId: this.credentials?.environmentId ? 'set' : 'not_set',
      clientId: this.credentials?.clientId ? 'set' : 'not_set',
      ...data
    };
    console.log('Credentials Modal Event:', eventData);
 
    // You can also send this to your logging system
    // fetch('/api/logs', { method: 'POST', body: JSON.stringify(eventData) });
  }
 
  /**
   * Check if credentials are already properly saved and working
   * @returns {Promise<boolean>} True if credentials are saved and working
   */
  static async areCredentialsSaved() {
    try {
      const response = await fetch('/api/settings');
      if (!response.ok) {
        return false;
      }
      const data = await response.json();
      const settings = data.data || data.settings || {};
 
      // Check if we have all required credentials
      const hasRequiredCredentials = settings.environmentId && settings.apiClientId && settings.apiSecret;
      if (!hasRequiredCredentials) {
        return false;
      }
 
      // Try to get a token to verify credentials work
      if (window.app && window.app.pingOneClient) {
        try {
          const token = await window.app.pingOneClient.getAccessToken();
          return !!token;
        } catch (error) {
          console.warn('Credentials exist but token acquisition failed:', error);
          return false;
        }
      }
      return true;
    } catch (error) {
      console.error('Error checking if credentials are saved:', error);
      return false;
    }
  }
 
  /**
   * Check if the credentials modal should be shown
   * @returns {Promise<boolean>} True if modal should be shown
   */
  static async shouldShowCredentialsModal() {
    // TEMPORARY: Force credentials modal to always show for debugging
    console.log('DEBUGGING: Forcing credentials modal to show');
    return true;
 
    // Original logic (commented out for debugging):
    // try {
    //     // Check if modal was already shown in this session
    //     const modalShown = sessionStorage.getItem('credentials_modal_shown');
    //     if (modalShown === 'true') {
    //         console.log('Credentials modal already shown in this session');
    //         return false;
    //     }
    //     
    //     // Always show modal on startup to ask user about stored credentials
    //     // This gives users the choice to use stored credentials or configure new ones
    //     console.log('Showing credentials modal on startup to ask about stored credentials');
    //     return true;
    //     
    // } catch (error) {
    //     console.error('Error checking if credentials modal should be shown:', error);
    //     return true; // Show modal on error to be safe
    // }
  }
 
  /**
   * Mark that the credentials modal has been shown
   */
  static setCredentialsModalShown() {
    sessionStorage.setItem('credentials_modal_shown', 'true');
    console.log('Credentials modal marked as shown for this session');
  }
 
  /**
   * Reset the credentials modal state (for testing or re-showing)
   */
  static resetCredentialsModal() {
    sessionStorage.removeItem('credentials_modal_shown');
    console.log('Credentials modal state reset');
  }
 
  // Static method to check if there's a valid token
  static hasValidToken() {
    try {
      const token = localStorage.getItem('pingone_worker_token');
      const expiry = localStorage.getItem('pingone_token_expiry');
      if (!token || !expiry) {
        return false;
      }
      const expiryTime = parseInt(expiry, 10);
      const now = Date.now();
      const timeRemaining = expiryTime - now;
      return timeRemaining > 0;
    } catch (error) {
      console.error('Error checking token validity:', error);
      return false;
    }
  }
}
 
// Initialize credentials modal when DOM is loaded
document.addEventListener('DOMContentLoaded', async () => {
  console.log('Credentials Modal: DOMContentLoaded event fired');
  console.log('Disclaimer accepted:', DisclaimerModal.isDisclaimerAccepted());
  console.log('Credentials modal shown:', sessionStorage.getItem('credentials_modal_shown'));
 
  // Check if disclaimer is already accepted (user returning)
  if (DisclaimerModal.isDisclaimerAccepted()) {
    const shouldShow = await CredentialsModal.shouldShowCredentialsModal();
    console.log('Should show credentials modal:', shouldShow);
    if (shouldShow) {
      console.log('Credentials Modal: Showing modal for returning user');
      // Small delay to ensure disclaimer modal is fully closed
      setTimeout(() => {
        new CredentialsModal();
        CredentialsModal.setCredentialsModalShown();
      }, 1000);
    }
  }
});
 
// Listen for disclaimer completion events
document.addEventListener('disclaimerAccepted', async event => {
  console.log('Credentials Modal: Disclaimer accepted event received', event.detail);
  // Wait a bit longer for disclaimer modal to fully close
  setTimeout(async () => {
    console.log('Credentials Modal: Checking if should show after disclaimer');
    const shouldShow = await CredentialsModal.shouldShowCredentialsModal();
    console.log('Should show credentials modal:', shouldShow);
    if (shouldShow) {
      console.log('Credentials Modal: Creating modal after disclaimer acceptance');
      new CredentialsModal();
      CredentialsModal.setCredentialsModalShown();
    }
  }, 1500);
});
 
// Listen for token status changes
document.addEventListener('token-updated', async event => {
  console.log('Credentials Modal: Token updated event received', event.detail);
  // Check if we should show credentials modal when token changes
  setTimeout(async () => {
    const shouldShow = await CredentialsModal.shouldShowCredentialsModal();
    console.log('Should show credentials modal after token update:', shouldShow);
    if (shouldShow) {
      console.log('Credentials Modal: Creating modal after token update');
      new CredentialsModal();
      CredentialsModal.setCredentialsModalShown();
    }
  }, 1000);
});
 
// Periodic check for token status (every 5 minutes)
setInterval(async () => {
  if (DisclaimerModal.isDisclaimerAccepted()) {
    const shouldShow = await CredentialsModal.shouldShowCredentialsModal();
    if (shouldShow) {
      console.log('Credentials Modal: Periodic check - showing modal');
      new CredentialsModal();
      CredentialsModal.setCredentialsModalShown();
    }
  }
}, 5 * 60 * 1000); // 5 minutes
 
// Export for testing
if (typeof module !== 'undefined' && module.exports) {
  module.exports = CredentialsModal;
}
 
},{}],45:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.cryptoUtils = exports.CryptoUtils = void 0;
// File: crypto-utils.js
// Description: Cryptographic utilities for secure data handling
// 
// This module provides encryption and decryption functionality for
// sensitive data like API secrets and user credentials. Uses the
// Web Crypto API for secure cryptographic operations.
// 
// Features:
// - PBKDF2 key derivation for secure key generation
// - AES-GCM encryption for authenticated encryption
// - Base64 encoding for storage compatibility
// - Error handling for decryption failures
 
/**
 * Cryptographic Utilities Class
 * 
 * Provides secure encryption and decryption using the Web Crypto API.
 * Uses PBKDF2 for key derivation and AES-GCM for authenticated encryption.
 * All methods are static for easy use throughout the application.
 */
class CryptoUtils {
  /**
   * Generate a cryptographic key for encryption/decryption
   * 
   * Uses PBKDF2 key derivation to create a secure key from a password.
   * The key is suitable for AES-GCM encryption operations.
   * 
   * @param {string} password - The password to derive the key from
   * @returns {Promise<CryptoKey>} A CryptoKey object for encryption/decryption
   */
  static async generateKey(password) {
    // Convert password to key material using PBKDF2
    const encoder = new TextEncoder();
    const keyMaterial = await window.crypto.subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, ['deriveBits', 'deriveKey']);
 
    // Derive the actual encryption key using PBKDF2
    return window.crypto.subtle.deriveKey({
      name: 'PBKDF2',
      salt: new TextEncoder().encode('PingOneImportSalt'),
      // Should be unique per user in production
      iterations: 100000,
      hash: 'SHA-256'
    }, keyMaterial, {
      name: 'AES-GCM',
      length: 256
    }, false, ['encrypt', 'decrypt']);
  }
 
  /**
   * Encrypt a string using AES-GCM
   * 
   * Encrypts text using AES-GCM with a random initialization vector (IV).
   * The IV is prepended to the encrypted data for secure storage.
   * Returns the result as base64-encoded string.
   * 
   * @param {string} text - The text to encrypt
   * @param {CryptoKey} key - The encryption key
   * @returns {Promise<string>} Encrypted text as base64 string
   */
  static async encrypt(text, key) {
    // Convert text to UTF-8 bytes
    const encoder = new TextEncoder();
    const data = encoder.encode(text);
 
    // Generate a random IV (Initialization Vector) for security
    const iv = window.crypto.getRandomValues(new Uint8Array(12));
 
    // Encrypt the data using AES-GCM
    const encrypted = await window.crypto.subtle.encrypt({
      name: 'AES-GCM',
      iv
    }, key, data);
 
    // Combine IV and encrypted data into a single array
    // IV is prepended for secure storage and retrieval
    const result = new Uint8Array(iv.length + encrypted.byteLength);
    result.set(iv, 0);
    result.set(new Uint8Array(encrypted), iv.length);
 
    // Convert to base64 for storage compatibility
    return btoa(String.fromCharCode(...result));
  }
 
  /**
   * Decrypt a string
   * @param {string} encryptedBase64 - The encrypted text in base64 format
   * @param {CryptoKey} key - The decryption key
   * @returns {Promise<string>} Decrypted text
   */
  static async decrypt(encryptedBase64, key) {
    try {
      // Convert from base64 to Uint8Array
      const encryptedData = Uint8Array.from(atob(encryptedBase64), c => c.charCodeAt(0));
 
      // Extract the IV (first 12 bytes)
      const iv = encryptedData.slice(0, 12);
      const data = encryptedData.slice(12);
      const decrypted = await window.crypto.subtle.decrypt({
        name: 'AES-GCM',
        iv
      }, key, data);
      return new TextDecoder().decode(decrypted);
    } catch (error) {
      // Don't log the error here - let the calling code handle it
      throw error;
    }
  }
}
 
// Export the class and a singleton instance
exports.CryptoUtils = CryptoUtils;
const cryptoUtils = exports.cryptoUtils = new CryptoUtils();
 
},{}],46:[function(require,module,exports){
"use strict";
 
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
/**
 * Disclaimer Modal Module
 * Enforces user acknowledgment before allowing access to the application
 */
class DisclaimerModal {
  constructor() {
    this.isActive = false;
    this.focusableElements = [];
    this.firstFocusableElement = null;
    this.lastFocusableElement = null;
    this.previousActiveElement = null;
    this.init();
  }
  init() {
    this.createModal();
    this.bindEvents();
    this.showModal();
  }
  createModal() {
    // Create modal overlay
    const overlay = document.createElement('div');
    overlay.className = 'disclaimer-modal-overlay';
    overlay.setAttribute('role', 'dialog');
    overlay.setAttribute('aria-modal', 'true');
    overlay.setAttribute('aria-labelledby', 'disclaimer-title');
    overlay.setAttribute('aria-describedby', 'disclaimer-content');
 
    // Create modal content
    overlay.innerHTML = `
            <div class="disclaimer-modal" tabindex="-1">
                <div class="disclaimer-modal-header">
                    <h2 id="disclaimer-title">
                        <span class="warning-icon" aria-hidden="true">⚠️</span>
                        <span>Important Disclaimer</span>
                    </h2>
                </div>
                
                <div class="disclaimer-modal-body">
                    <div id="disclaimer-content" class="disclaimer-content">
                        <h3>🚨 UNSUPPORTED TOOL WARNING</h3>
                        <p>
                            <strong>This tool is NOT an official Ping Identity product</strong> and is provided 
                            <span class="highlight">without any warranty or support</span>. Use at your own risk.
                        </p>
                        
                        <h3>⚠️ CRITICAL DISCLAIMERS:</h3>
                        <ul>
                            <li><strong>No technical support</strong> is available from Ping Identity</li>
                            <li><strong>No updates or bug fixes</strong> are guaranteed</li>
                            <li><strong>No compatibility</strong> with future PingOne versions is assured</li>
                            <li><strong>No documentation or training</strong> is provided by Ping Identity</li>
                            <li>This tool may <strong>stop working at any time</strong> without notice</li>
                            <li>Use of this tool is <strong>not recommended for production environments</strong></li>
                            <li>You are <strong>responsible for testing and validating</strong> all operations</li>
                            <li><strong>Backup your PingOne account</strong> before using this tool</li>
                            <li><strong>Test in non-production environments</strong> only</li>
                        </ul>
                        
                        <p>
                            <strong>By continuing, you acknowledge that:</strong>
                        </p>
                        <ul>
                            <li>You understand this tool is unsupported and use it at your own risk</li>
                            <li>You have backed up your PingOne account data</li>
                            <li>You will test operations in non-production environments first</li>
                            <li>You accept full responsibility for any data loss or issues</li>
                        </ul>
                    </div>
                </div>
                
                <div class="disclaimer-modal-footer">
                    <div class="disclaimer-agreement">
                        <div class="disclaimer-checkbox">
                            <input type="checkbox" id="disclaimer-agreement-checkbox" required>
                            <label for="disclaimer-agreement-checkbox">
                                <span class="required-indicator">*</span>
                                I acknowledge and accept the above disclaimer. I understand this tool is unsupported and I use it at my own risk.
                            </label>
                        </div>
                    </div>
                    
                    <div class="disclaimer-actions">
                        <button type="button" class="disclaimer-btn disclaimer-btn-secondary" id="disclaimer-cancel">
                            Cancel
                        </button>
                        <button type="button" class="disclaimer-btn disclaimer-btn-primary" id="disclaimer-continue" disabled>
                            Continue
                        </button>
                    </div>
                </div>
            </div>
        `;
    document.body.appendChild(overlay);
    this.overlay = overlay;
    this.modal = overlay.querySelector('.disclaimer-modal');
    this.checkbox = overlay.querySelector('#disclaimer-agreement-checkbox');
    this.continueBtn = overlay.querySelector('#disclaimer-continue');
    this.cancelBtn = overlay.querySelector('#disclaimer-cancel');
  }
  bindEvents() {
    // Checkbox change event
    this.checkbox.addEventListener('change', e => {
      this.continueBtn.disabled = !e.target.checked;
      this.logEvent('disclaimer_checkbox_changed', {
        checked: e.target.checked
      });
    });
 
    // Continue button click
    this.continueBtn.addEventListener('click', () => {
      this.acceptDisclaimer();
    });
 
    // Cancel button click
    this.cancelBtn.addEventListener('click', () => {
      this.cancelDisclaimer();
    });
 
    // Keyboard events for accessibility
    this.overlay.addEventListener('keydown', e => {
      this.handleKeyboardNavigation(e);
    });
 
    // Prevent clicks outside modal from closing it
    this.overlay.addEventListener('click', e => {
      if (e.target === this.overlay) {
        // Don't close on outside click - require explicit action
        this.logEvent('disclaimer_outside_click_prevented');
      }
    });
 
    // Escape key handling
    document.addEventListener('keydown', e => {
      if (e.key === 'Escape' && this.isActive) {
        e.preventDefault();
        this.cancelDisclaimer();
      }
    });
  }
  handleKeyboardNavigation(e) {
    if (!this.isActive) return;
    const focusableElements = this.getFocusableElements();
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];
 
    // Tab key navigation with focus trapping
    if (e.key === 'Tab') {
      if (e.shiftKey) {
        if (document.activeElement === firstElement) {
          e.preventDefault();
          lastElement.focus();
        }
      } else {
        if (document.activeElement === lastElement) {
          e.preventDefault();
          firstElement.focus();
        }
      }
    }
  }
  getFocusableElements() {
    const focusableSelectors = ['button:not([disabled])', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'a[href]', '[tabindex]:not([tabindex="-1"])'];
    return Array.from(this.modal.querySelectorAll(focusableSelectors.join(', ')));
  }
  showModal() {
    this.isActive = true;
    this.previousActiveElement = document.activeElement;
 
    // Add classes to body and app container
    document.body.classList.add('disclaimer-modal-open');
    const appContainer = document.querySelector('.app-container');
    if (appContainer) {
      appContainer.classList.add('disclaimer-modal-active');
    }
 
    // Show modal with animation
    this.overlay.classList.add('active');
 
    // Focus management
    this.modal.focus();
    this.setupFocusTrap();
    this.logEvent('disclaimer_modal_shown');
 
    // Announce to screen readers
    this.announceToScreenReader('Disclaimer modal opened. You must read and accept the disclaimer to continue.');
  }
  setupFocusTrap() {
    this.focusableElements = this.getFocusableElements();
    this.firstFocusableElement = this.focusableElements[0];
    this.lastFocusableElement = this.focusableElements[this.focusableElements.length - 1];
  }
  acceptDisclaimer() {
    if (!this.checkbox.checked) {
      this.logEvent('disclaimer_acceptance_attempted_without_checkbox');
      return;
    }
    this.logEvent('disclaimer_accepted');
    this.hideModal();
 
    // Enable application functionality
    this.enableApplication();
 
    // Call the app's enableToolAfterDisclaimer function to show startup screen
    if (typeof window.enableToolAfterDisclaimer === 'function') {
      console.log('[STARTUP] [DEBUG] Disclaimer accepted, calling enableToolAfterDisclaimer');
      window.enableToolAfterDisclaimer();
    } else {
      console.warn('[STARTUP] [DEBUG] enableToolAfterDisclaimer function not found');
    }
 
    // Dispatch custom event for other components to listen to
    document.dispatchEvent(new CustomEvent('disclaimerAccepted', {
      detail: {
        timestamp: new Date().toISOString()
      }
    }));
 
    // Announce to screen readers
    this.announceToScreenReader('Disclaimer accepted. Application is now enabled.');
  }
  cancelDisclaimer() {
    this.logEvent('disclaimer_cancelled');
    this.hideModal();
 
    // Show warning that application cannot be used without accepting
    this.showCancellationWarning();
  }
  hideModal() {
    this.isActive = false;
 
    // Remove classes
    document.body.classList.remove('disclaimer-modal-open');
    const appContainer = document.querySelector('.app-container');
    if (appContainer) {
      appContainer.classList.remove('disclaimer-modal-active');
    }
 
    // Hide modal with animation
    this.overlay.classList.remove('active');
 
    // Restore focus
    if (this.previousActiveElement) {
      this.previousActiveElement.focus();
    }
 
    // Announce to screen readers
    this.announceToScreenReader('Disclaimer modal closed.');
  }
  enableApplication() {
    // Remove disabled state from all interactive elements
    const disabledElements = document.querySelectorAll('[disabled]');
    disabledElements.forEach(el => {
      if (el.classList.contains('disclaimer-disabled')) {
        el.disabled = false;
        el.classList.remove('disclaimer-disabled');
      }
    });
 
    // Enable navigation
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
      item.style.pointerEvents = 'auto';
      item.style.opacity = '1';
    });
 
    // Enable feature cards
    const featureCards = document.querySelectorAll('.feature-card');
    featureCards.forEach(card => {
      card.style.pointerEvents = 'auto';
      card.style.opacity = '1';
    });
 
    // Store acceptance
    DisclaimerModal.setDisclaimerAccepted();
    this.logEvent('application_enabled_after_disclaimer');
  }
  showCancellationWarning() {
    // Create a temporary warning message
    const warning = document.createElement('div');
    warning.className = 'alert alert-warning alert-dismissible fade show';
    warning.style.position = 'fixed';
    warning.style.top = '20px';
    warning.style.left = '50%';
    warning.style.transform = 'translateX(-50%)';
    warning.style.zIndex = '10000';
    warning.style.maxWidth = '500px';
    warning.innerHTML = `
            <strong>⚠️ Disclaimer Required</strong>
            <br>You must accept the disclaimer to use this tool. The application will remain disabled until you acknowledge the terms.
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;
    document.body.appendChild(warning);
 
    // Auto-remove after 10 seconds
    setTimeout(() => {
      if (warning.parentNode) {
        warning.remove();
      }
    }, 10000);
    this.logEvent('disclaimer_cancellation_warning_shown');
  }
  announceToScreenReader(message) {
    // Create temporary element for screen reader announcement
    const announcement = document.createElement('div');
    announcement.setAttribute('aria-live', 'polite');
    announcement.setAttribute('aria-atomic', 'true');
    announcement.className = 'sr-only';
    announcement.textContent = message;
    document.body.appendChild(announcement);
 
    // Remove after announcement
    setTimeout(() => {
      if (announcement.parentNode) {
        announcement.remove();
      }
    }, 1000);
  }
  logEvent(eventName) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    // Log to console for debugging
    console.log(`[DisclaimerModal] ${eventName}:`, data);
 
    // Send to server if logging is available and properly initialized
    try {
      // Check if logManager exists and has the log method
      if (window.logManager && typeof window.logManager.log === 'function') {
        window.logManager.log('info', `Disclaimer modal: ${eventName}`, {
          source: 'disclaimer-modal',
          type: 'ui',
          ...data
        });
      } else if (window.logManager) {
        // logManager exists but doesn't have log method - initialize it
        if (typeof window.logManager.log !== 'function') {
          window.logManager.log = function (level, message, data) {
            const timestamp = new Date().toISOString();
            const logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
            if (data) {
              console.log(logMessage, data);
            } else {
              console.log(logMessage);
            }
          };
          // Now try logging again
          window.logManager.log('info', `Disclaimer modal: ${eventName}`, {
            source: 'disclaimer-modal',
            type: 'ui',
            ...data
          });
        }
      } else {
        // logManager not available - create a basic one
        window.logManager = {
          log: function (level, message, data) {
            const timestamp = new Date().toISOString();
            const logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
            if (data) {
              console.log(logMessage, data);
            } else {
              console.log(logMessage);
            }
          }
        };
        // Now try logging
        window.logManager.log('info', `Disclaimer modal: ${eventName}`, {
          source: 'disclaimer-modal',
          type: 'ui',
          ...data
        });
      }
    } catch (error) {
      // Graceful fallback if logging fails
      console.warn('[DisclaimerModal] Logging failed:', error);
    }
  }
 
  // === CONFIGURATION ===
  // Set to true for session-only disclaimer (shows once per browser session)
 
  // e.g. 7 days, or 0 for no expiry
 
  // Static method to check if disclaimer was previously accepted (with expiry/session logic)
  static isDisclaimerAccepted() {
    // TEMPORARY: Force disclaimer to always show for debugging
    return false;
 
    // Original logic (commented out for debugging):
    // if (DisclaimerModal.DISCLAIMER_SESSION_ONLY) {
    //     return sessionStorage.getItem('disclaimerAccepted') === 'true';
    // }
    // // Expiry logic
    // const accepted = localStorage.getItem('disclaimerAccepted') === 'true';
    // if (!accepted) return false;
    // if (DisclaimerModal.DISCLAIMER_EXPIRY_DAYS > 0) {
    //     const acceptedAt = localStorage.getItem('disclaimerAcceptedAt');
    //     if (!acceptedAt) return false;
    //     const acceptedDate = new Date(acceptedAt);
    //     const now = new Date();
    //     const diffDays = (now - acceptedDate) / (1000 * 60 * 60 * 24);
    //     if (diffDays > DisclaimerModal.DISCLAIMER_EXPIRY_DAYS) {
    //         // Expired, reset
    //         DisclaimerModal.resetDisclaimerAcceptance();
    //         return false;
    //     }
    // }
    // return true;
  }
 
  // Static method to set acceptance (handles session/local/expiry)
  static setDisclaimerAccepted() {
    if (DisclaimerModal.DISCLAIMER_SESSION_ONLY) {
      sessionStorage.setItem('disclaimerAccepted', 'true');
    } else {
      localStorage.setItem('disclaimerAccepted', 'true');
      localStorage.setItem('disclaimerAcceptedAt', new Date().toISOString());
    }
  }
 
  // Static method to reset disclaimer acceptance
  static resetDisclaimerAcceptance() {
    if (DisclaimerModal.DISCLAIMER_SESSION_ONLY) {
      sessionStorage.removeItem('disclaimerAccepted');
    } else {
      localStorage.removeItem('disclaimerAccepted');
      localStorage.removeItem('disclaimerAcceptedAt');
    }
  }
}
 
// Initialize disclaimer modal immediately (DOM is already loaded when bundle executes)
(0, _defineProperty2.default)(DisclaimerModal, "DISCLAIMER_SESSION_ONLY", false);
// set true for sessionStorage, false for localStorage
// Set expiry in days (set to 0 for no expiry)
(0, _defineProperty2.default)(DisclaimerModal, "DISCLAIMER_EXPIRY_DAYS", 7);
(function () {
  console.log('[DISCLAIMER DEBUG] Modal initialization starting immediately');
 
  // Wait for app to be fully initialized before showing disclaimer
  let disclaimerInitialized = false;
  const initializeDisclaimer = () => {
    console.log('[DISCLAIMER DEBUG] initializeDisclaimer called, disclaimerInitialized:', disclaimerInitialized);
    if (disclaimerInitialized) return;
 
    // Ensure logManager is available before proceeding
    if (!window.logManager) {
      console.log('[DISCLAIMER DEBUG] Creating logManager');
      window.logManager = {
        log: function (level, message, data) {
          const timestamp = new Date().toISOString();
          const logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
          if (data) {
            console.log(logMessage, data);
          } else {
            console.log(logMessage);
          }
        }
      };
    }
 
    // Check disclaimer acceptance status
    const isAccepted = DisclaimerModal.isDisclaimerAccepted();
    console.log('[DISCLAIMER DEBUG] isDisclaimerAccepted():', isAccepted);
 
    // Only show disclaimer if not previously accepted (with expiry/session logic)
    if (!isAccepted) {
      console.log('[DISCLAIMER DEBUG] Creating new DisclaimerModal');
      new DisclaimerModal();
      disclaimerInitialized = true;
    } else {
      console.log('[DISCLAIMER DEBUG] Disclaimer previously accepted, not showing modal');
      // If previously accepted, just enable the application (no modal)
      if (typeof window.enableToolAfterDisclaimer === 'function') {
        console.log('[STARTUP] [DEBUG] Disclaimer previously accepted, calling enableToolAfterDisclaimer');
        window.enableToolAfterDisclaimer();
      } else {
        console.warn('[STARTUP] [DEBUG] enableToolAfterDisclaimer function not found');
      }
      disclaimerInitialized = true;
    }
  };
 
  // Try to initialize immediately
  initializeDisclaimer();
  // Also try after a short delay to ensure app components are loaded
  setTimeout(initializeDisclaimer, 100);
  // Final attempt after longer delay to ensure logManager is available
  setTimeout(initializeDisclaimer, 1000);
  // Additional attempt after app initialization
  setTimeout(initializeDisclaimer, 2000);
})();
 
// Export for global access
window.DisclaimerModal = DisclaimerModal;
 
},{"@babel/runtime/helpers/defineProperty":1,"@babel/runtime/helpers/interopRequireDefault":2}],47:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ElementRegistry = void 0;
// ElementRegistry: Centralized DOM element lookup utility
// Provides safe, memoized access to all required UI elements with logging for missing elements
// Usage: import { ElementRegistry } from './element-registry.js';
 
const elementCache = {};
function getElement(selector, description) {
  let required = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  // Input validation
  if (!selector || typeof selector !== 'string') {
    console.error(`[ElementRegistry] Invalid selector provided: ${selector}`);
    return null;
  }
 
  // Security: Prevent potential XSS through selector injection
  // Allow valid attribute selectors with quotes but prevent script injection
  if (selector.includes('<') || selector.includes('>') || selector.includes('"') && !selector.includes('[') && !selector.includes(']') || selector.includes("'") && !selector.includes('[') && !selector.includes(']')) {
    console.error(`[ElementRegistry] Potentially unsafe selector detected: ${selector}`);
    return null;
  }
 
  // Check cache first
  if (elementCache[selector]) {
    return elementCache[selector];
  }
  try {
    const el = document.querySelector(selector);
    if (!el && required) {
      console.warn(`[ElementRegistry] Missing required element: ${description} (${selector})`);
    } else if (!el) {
      console.info(`[ElementRegistry] Optional element not found: ${description} (${selector})`);
    } else {
      // Validate element is still in DOM
      if (!document.contains(el)) {
        console.warn(`[ElementRegistry] Element found but not in DOM: ${description} (${selector})`);
        elementCache[selector] = null;
        return null;
      }
    }
    elementCache[selector] = el;
    return el;
  } catch (error) {
    console.error(`[ElementRegistry] Error finding element: ${description} (${selector})`, error);
    elementCache[selector] = null;
    return null;
  }
}
const ElementRegistry = exports.ElementRegistry = {
  // Main UI elements
  importButton: () => getElement('#import-btn', 'Import Button'),
  fileInput: () => getElement('#csv-file', 'File Input'),
  dashboardTab: () => getElement('#dashboard-tab', 'Dashboard Tab'),
  dragDropArea: () => getElement('#drag-drop-area', 'Drag-and-Drop Area', false),
  // Notification and progress containers
  notificationContainer: () => getElement('#notification-area', 'Notification Container'),
  progressContainer: () => {
    // Try specific progress containers first, then fallback to generic
    return getElement('#import-progress-container', 'Import Progress Container', false) || getElement('#delete-progress-container', 'Delete Progress Container', false) || getElement('#modify-progress-container', 'Modify Progress Container', false) || getElement('#export-progress-container', 'Export Progress Container', false) || getElement('#progress-container', 'Progress Container', false) || getElement('.progress-container', 'Progress Container (class)', false);
  },
  // Token and connection status elements
  tokenStatus: () => getElement('#token-status-indicator', 'Token Status'),
  connectionStatus: () => getElement('#connection-status', 'Connection Status'),
  currentTokenStatus: () => getElement('#current-token-status', 'Current Token Status'),
  homeTokenStatus: () => getElement('#home-token-status', 'Home Token Status'),
  // File handling elements
  fileInfo: () => getElement('#file-info', 'File Info'),
  previewContainer: () => getElement('#dashboard-preview', 'Preview Container'),
  fileInputLabel: () => getElement('label[for="csv-file"]', 'File Input Label'),
  deleteFileInput: () => getElement('#delete-csv-file', 'Delete File Input'),
  deleteFileInputLabel: () => getElement('label[for="delete-csv-file"]', 'Delete File Input Label'),
  modifyFileInput: () => getElement('#modify-csv-file', 'Modify File Input'),
  modifyFileInputLabel: () => getElement('label[for="modify-csv-file"]', 'Modify File Input Label'),
  // Population selection elements
  importPopulationSelect: () => getElement('#import-population-select', 'Import Population Select'),
  deletePopulationSelect: () => getElement('#delete-population-select', 'Delete Population Select'),
  modifyPopulationSelect: () => getElement('#modify-population-select', 'Modify Population Select'),
  dashboardPopulationSelect: () => getElement('#dashboard-population-select', 'Dashboard Population Select'),
  // Import buttons
  startImportBtn: () => getElement('#start-import', 'Start Import Button'),
  startImportBtnBottom: () => getElement('#bottom-start-import', 'Bottom Start Import Button'),
  // Settings elements
  settingsSaveStatus: () => getElement('#settings-save-status', 'Settings Save Status'),
  // Import status elements
  importStatus: () => getElement('#import-status', 'Import Status'),
  // Population checkboxes
  useDefaultPopulationCheckbox: () => getElement('#use-default-population', 'Use Default Population Checkbox'),
  useCsvPopulationIdCheckbox: () => getElement('#use-csv-population-id', 'Use CSV Population ID Checkbox'),
  // Get Token button
  getTokenBtn: () => getElement('#get-token-quick', 'Get Token Button'),
  // Population ID form field
  populationIdField: () => getElement('#population-id', 'Population ID Field')
};
 
// Global exports for subsystem access
if (typeof window !== 'undefined') {
  window.getElement = getElement;
  window.elementCache = elementCache;
  window.ElementRegistry = ElementRegistry;
  console.log('✅ Element registry global exports initialized');
}
 
},{}],48:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ErrorTypes = exports.ErrorSeverity = exports.ErrorMetadata = exports.ErrorMessages = exports.ErrorCodes = void 0;
exports.createError = createError;
exports.getDefaultMessage = getDefaultMessage;
exports.getDefaultSeverity = getDefaultSeverity;
exports.isErrorType = isErrorType;
/**
 * Error Types
 * 
 * Defines standard error types and severities for consistent error handling
 */
 
/**
 * Standard error types
 */
const ErrorTypes = exports.ErrorTypes = Object.freeze({
  // Client-side errors
  VALIDATION: 'VALIDATION',
  // Data validation failed
  AUTHENTICATION: 'AUTHENTICATION',
  // Authentication/authorization issues
  AUTHORIZATION: 'AUTHORIZATION',
  // Permission issues
  NETWORK: 'NETWORK',
  // Network connectivity issues
  TIMEOUT: 'TIMEOUT',
  // Request timeouts
 
  // Server-side errors
  SERVER: 'SERVER',
  // Generic server error (500)
  SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',
  // Service unavailable (503)
  NOT_FOUND: 'NOT_FOUND',
  // Resource not found (404)
  CONFLICT: 'CONFLICT',
  // Resource conflict (409)
 
  // Application-specific errors
  CONFIGURATION: 'CONFIGURATION',
  // Configuration errors
  INTEGRATION: 'INTEGRATION',
  // Third-party service integration errors
 
  // Fallback
  UNKNOWN: 'UNKNOWN' // Unclassified errors
});
 
/**
 * Error severity levels
 */
const ErrorSeverity = exports.ErrorSeverity = Object.freeze({
  FATAL: 'FATAL',
  // Application cannot continue
  ERROR: 'ERROR',
  // Operation failed, but application can continue
  WARNING: 'WARNING',
  // Operation completed with issues
  INFO: 'INFO',
  // Informational message
  DEBUG: 'DEBUG' // Debug information
});
 
/**
 * Standard error codes
 */
const ErrorCodes = exports.ErrorCodes = Object.freeze({
  // Authentication (1000-1099)
  INVALID_CREDENTIALS: 1001,
  SESSION_EXPIRED: 1002,
  INVALID_TOKEN: 1003,
  // Validation (2000-2099)
  INVALID_INPUT: 2001,
  MISSING_REQUIRED_FIELD: 2002,
  INVALID_FORMAT: 2003,
  // Authorization (3000-3099)
  PERMISSION_DENIED: 3001,
  INSUFFICIENT_PERMISSIONS: 3002,
  // Network (4000-4099)
  NETWORK_ERROR: 4001,
  REQUEST_TIMEOUT: 4002,
  // Server (5000-5099)
  INTERNAL_SERVER_ERROR: 5001,
  SERVICE_UNAVAILABLE: 5002,
  // Business Logic (6000-6099)
  DUPLICATE_ENTRY: 6001,
  RESOURCE_NOT_FOUND: 6002,
  // Integration (7000-7099)
  EXTERNAL_SERVICE_ERROR: 7001,
  API_RATE_LIMIT_EXCEEDED: 7002
});
 
/**
 * Standard error messages
 */
const ErrorMessages = exports.ErrorMessages = Object.freeze({
  [ErrorTypes.VALIDATION]: 'Validation failed',
  [ErrorTypes.AUTHENTICATION]: 'Authentication required',
  [ErrorTypes.AUTHORIZATION]: 'Permission denied',
  [ErrorTypes.NETWORK]: 'Network error occurred',
  [ErrorTypes.TIMEOUT]: 'Request timed out',
  [ErrorTypes.SERVER]: 'Internal server error',
  [ErrorTypes.SERVICE_UNAVAILABLE]: 'Service unavailable',
  [ErrorTypes.NOT_FOUND]: 'Resource not found',
  [ErrorTypes.CONFLICT]: 'Resource conflict',
  [ErrorTypes.CONFIGURATION]: 'Configuration error',
  [ErrorTypes.INTEGRATION]: 'Integration error',
  [ErrorTypes.UNKNOWN]: 'An unexpected error occurred'
});
 
/**
 * Error metadata
 * Maps error types to their default properties
 */
const ErrorMetadata = exports.ErrorMetadata = Object.freeze({
  [ErrorTypes.VALIDATION]: {
    severity: ErrorSeverity.WARNING,
    isRecoverable: true,
    userMessage: 'Please check your input and try again.'
  },
  [ErrorTypes.AUTHENTICATION]: {
    severity: ErrorSeverity.ERROR,
    isRecoverable: true,
    userMessage: 'Your session has expired. Please log in again.'
  },
  [ErrorTypes.AUTHORIZATION]: {
    severity: ErrorSeverity.ERROR,
    isRecoverable: false,
    userMessage: 'You do not have permission to perform this action.'
  },
  [ErrorTypes.NETWORK]: {
    severity: ErrorSeverity.WARNING,
    isRecoverable: true,
    userMessage: 'Unable to connect to the server. Please check your internet connection.'
  },
  [ErrorTypes.SERVER]: {
    severity: ErrorSeverity.ERROR,
    isRecoverable: false,
    userMessage: 'An unexpected server error occurred. Please try again later.'
  },
  [ErrorTypes.UNKNOWN]: {
    severity: ErrorSeverity.ERROR,
    isRecoverable: false,
    userMessage: 'An unexpected error occurred. Please try again.'
  }
});
 
/**
 * Creates a standard error object
 * @param {string} type - Error type from ErrorTypes
 * @param {string} message - Error message
 * @param {Object} details - Additional error details
 * @returns {Error} Standardized error object
 */
function createError(type, message) {
  let details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  const error = new Error(message || ErrorMessages[type] || 'An unknown error occurred');
  error.type = type;
  error.code = details.code || ErrorCodes[type] || 0;
  error.details = details;
  error.timestamp = new Date().toISOString();
 
  // Add metadata if available
  const metadata = ErrorMetadata[type];
  if (metadata) {
    error.severity = metadata.severity;
    error.isRecoverable = metadata.isRecoverable;
    error.userMessage = metadata.userMessage;
  }
  return error;
}
 
/**
 * Checks if an error is of a specific type
 * @param {Error} error - The error to check
 * @param {string} type - The error type to check against
 * @returns {boolean} True if the error is of the specified type
 */
function isErrorType(error, type) {
  return error && error.type === type;
}
 
/**
 * Gets the default error message for an error type
 * @param {string} type - The error type
 * @returns {string} The default error message
 */
function getDefaultMessage(type) {
  return ErrorMessages[type] || 'An unknown error occurred';
}
 
/**
 * Gets the default severity for an error type
 * @param {string} type - The error type
 * @returns {string} The default severity
 */
function getDefaultSeverity(type) {
  const metadata = ErrorMetadata[type];
  return metadata ? metadata.severity : ErrorSeverity.ERROR;
}
 
},{}],49:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.eventBus = exports.default = exports.EventBus = void 0;
// event-bus.js
// Simple EventBus utility for cross-subsystem communication
 
class EventBus {
  constructor() {
    this.events = {};
  }
  on(event, handler) {
    (this.events[event] = this.events[event] || []).push(handler);
  }
  off(event, handler) {
    if (!this.events[event]) return;
    this.events[event] = this.events[event].filter(h => h !== handler);
  }
  emit(event, data) {
    (this.events[event] || []).forEach(h => h(data));
  }
}
 
// Create and export a default instance
exports.EventBus = EventBus;
const eventBus = exports.eventBus = new EventBus();
 
// Export both the class and the default instance
var _default = exports.default = eventBus; // Browser global fallback for legacy compatibility
if (typeof window !== 'undefined') {
  window.EventBus = EventBus;
  window.eventBus = eventBus;
}
 
},{}],50:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FileHandler = void 0;
var _elementRegistry = require("./element-registry.js");
// File: file-handler.js
// Description: CSV file processing and validation for PingOne user import
// 
// This module handles all file-related operations including:
// - CSV file reading and parsing
// - User data validation and error checking
// - File preview generation
// - File information display and management
// - Folder path tracking for better UX
// - Validation summary and error reporting
// 
// Provides comprehensive CSV processing with detailed validation feedback.
 
/**
 * File Handler Class
 * 
 * Manages CSV file processing, validation, and user data preparation
 * for the PingOne import tool. Handles file selection, parsing,
 * validation, and preview generation.
 * 
 * @param {Object} logger - Logger instance for debugging
 * @param {Object} uiManager - UI manager for status updates
 */
class FileHandler {
  /**
   * Create a new FileHandler instance
   * @param {Object} logger - Logger instance for debugging
   * @param {Object} uiManager - UI manager for status updates
   */
  constructor(logger, uiManager) {
    if (!logger) {
      throw new Error('Logger is required for FileHandler');
    }
    this.logger = logger;
    this.uiManager = uiManager;
 
    // Required fields for user validation
    this.requiredFields = ['username'];
 
    // Validation tracking for processed files
    this.validationResults = {
      total: 0,
      valid: 0,
      errors: 0,
      warnings: 0
    };
 
    // File processing state
    this.lastParsedUsers = [];
    this.currentFile = null;
 
    // Initialize UI elements for file handling
    this.fileInput = _elementRegistry.ElementRegistry.fileInput ? _elementRegistry.ElementRegistry.fileInput() : null;
    this.fileInfo = _elementRegistry.ElementRegistry.fileInfo ? _elementRegistry.ElementRegistry.fileInfo() : null;
    this.previewContainer = _elementRegistry.ElementRegistry.previewContainer ? _elementRegistry.ElementRegistry.previewContainer() : null;
 
    // Load last file info from localStorage for better UX
    this.lastFileInfo = this.loadLastFileInfo();
 
    // Initialize event listeners for file input
    this.initializeFileInput();
  }
 
  // ======================
  // File Info Management
  // ======================
 
  /**
   * Load last file info from localStorage
   * @returns {Object|null} Last file info or null if not found
   */
  loadLastFileInfo() {
    try {
      const savedFile = localStorage.getItem('lastSelectedFile');
      return savedFile ? JSON.parse(savedFile) : null;
    } catch (error) {
      this.logger.error('Error loading last file info:', error);
      return null;
    }
  }
 
  /**
   * Get the current file being processed
   * 
   * Returns the File object that is currently loaded and ready for processing.
   * Used by other modules to access the file for upload operations.
   * 
   * @returns {File|null} The current file or null if none is loaded
   */
  getCurrentFile() {
    return this.currentFile;
  }
 
  /**
   * Set a file and process it for import
   * 
   * Validates the file, processes its contents, and prepares it for
   * import operations. Updates UI with file information and validation results.
   * 
   * @param {File} file - The file to set and process
   * @param {string} operationType - The operation type ('import', 'delete', 'modify')
   * @returns {Promise<Object>} Promise that resolves with processing result
   */
  async setFile(file) {
    let operationType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'import';
    if (!file) {
      throw new Error('File is required for setFile operation');
    }
    try {
      this.logger.info('Setting file', {
        fileName: file.name,
        fileSize: file.size,
        operationType
      });
 
      // Store the current file reference for later use
      this.currentFile = file;
 
      // Process the file using the existing internal method
      // This includes validation, parsing, and UI updates
      await this._handleFileInternal(file, null, operationType);
      return {
        success: true,
        file
      };
    } catch (error) {
      this.logger.error('Failed to set file', {
        error: error.message,
        fileName: file.name,
        operationType
      });
      throw error;
    }
  }
 
  /**
   * Get the list of parsed users from the current file
   * 
   * Returns the array of user objects that were successfully parsed
   * from the CSV file. Each user object contains validated data.
   * 
   * @returns {Array} Array of user objects with validated data
   */
  getUsers() {
    return this.lastParsedUsers || [];
  }
 
  /**
   * Get the total number of users parsed from the CSV file
   * 
   * Returns the total count of users found in the processed CSV file.
   * This count includes all rows, regardless of validation status.
   * 
   * @returns {number} Total number of users in the CSV file
   */
  getTotalUsers() {
    const totalUsers = this.validationResults.total || 0;
    console.log('[CSV] getTotalUsers() called, returning:', totalUsers, 'validationResults:', this.validationResults);
    return totalUsers;
  }
 
  /**
   * Read file as text using FileReader API
   * 
   * Asynchronously reads a file and returns its contents as a string.
   * Used for processing CSV files and other text-based formats.
   * 
   * @param {File} file - The file to read
   * @returns {Promise<string>} Promise that resolves with file content as string
   */
  readFileAsText(file) {
    if (!file) {
      throw new Error('File is required for reading');
    }
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = event => resolve(event.target.result);
      reader.onerror = () => reject(new Error('Failed to read file'));
      reader.readAsText(file);
    });
  }
 
  /**
   * Save the last folder path that was used
   * @param {File} file - The selected file
   * @param {string} operationType - The operation type ('import', 'delete', 'modify')
   */
  saveLastFolderPath(file) {
    let operationType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'import';
    if (!file) {
      return;
    }
    try {
      let folderPath = null;
 
      // Try to extract folder path from different sources
      if (file.webkitRelativePath) {
        // For webkitRelativePath, get the directory part
        const pathParts = file.webkitRelativePath.split('/');
        if (pathParts.length > 1) {
          folderPath = pathParts.slice(0, -1).join('/');
        }
      } else if (file.name) {
        // For regular files, try to extract from the file name
        // This is a fallback since we can't get the full path due to security restrictions
        const fileName = file.name;
        const lastSlashIndex = fileName.lastIndexOf('/');
        if (lastSlashIndex !== -1) {
          folderPath = fileName.substring(0, lastSlashIndex);
        }
      }
      if (folderPath) {
        // Save with operation-specific key
        const storageKey = `lastFolderPath_${operationType}`;
        localStorage.setItem(storageKey, folderPath);
        this.logger.info(`Saved last folder path for ${operationType}:`, folderPath);
      }
 
      // Also save a general last folder path
      if (folderPath) {
        localStorage.setItem('lastFolderPath', folderPath);
      }
    } catch (error) {
      this.logger.warn('Could not save folder path:', error.message);
    }
  }
 
  /**
   * Get the last folder path that was used
   * @param {string} operationType - The operation type ('import', 'delete', 'modify')
   * @returns {string|null} The last folder path or null if not available
   */
  getLastFolderPath() {
    let operationType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'import';
    try {
      // First try to get operation-specific folder path
      const operationKey = `lastFolderPath_${operationType}`;
      let folderPath = localStorage.getItem(operationKey);
 
      // Fall back to general last folder path
      if (!folderPath) {
        folderPath = localStorage.getItem('lastFolderPath');
      }
      return folderPath;
    } catch (error) {
      this.logger.warn('Could not get last folder path:', error.message);
      return null;
    }
  }
 
  /**
   * Update the file input label to show last folder path
   * @param {string} operationType - The operation type ('import', 'delete', 'modify')
   */
  updateFileLabel() {
    let operationType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'import';
    try {
      // Find the appropriate file label based on operation type
      let fileLabel = null;
      let fileInput = null;
      switch (operationType) {
        case 'import':
          fileLabel = _elementRegistry.ElementRegistry.fileInputLabel ? _elementRegistry.ElementRegistry.fileInputLabel() : null;
          fileInput = _elementRegistry.ElementRegistry.fileInput ? _elementRegistry.ElementRegistry.fileInput() : null;
          break;
        case 'delete':
          fileLabel = _elementRegistry.ElementRegistry.deleteFileInputLabel ? _elementRegistry.ElementRegistry.deleteFileInputLabel() : null;
          fileInput = _elementRegistry.ElementRegistry.deleteFileInput ? _elementRegistry.ElementRegistry.deleteFileInput() : null;
          break;
        case 'modify':
          fileLabel = _elementRegistry.ElementRegistry.modifyFileInputLabel ? _elementRegistry.ElementRegistry.modifyFileInputLabel() : null;
          fileInput = _elementRegistry.ElementRegistry.modifyFileInput ? _elementRegistry.ElementRegistry.modifyFileInput() : null;
          break;
        default:
          fileLabel = _elementRegistry.ElementRegistry.fileInputLabel ? _elementRegistry.ElementRegistry.fileInputLabel() : null;
          break;
      }
      if (fileLabel) {
        const lastFolderPath = this.getLastFolderPath(operationType);
        if (lastFolderPath) {
          // Show a shortened version of the path for better UI
          const shortPath = this.shortenPath(lastFolderPath);
          fileLabel.textContent = `Choose CSV File (Last: ${shortPath})`;
          fileLabel.title = `Last used folder: ${lastFolderPath}`;
        } else {
          fileLabel.textContent = 'Choose CSV File';
          fileLabel.title = 'Select a CSV file to process';
        }
      }
    } catch (error) {
      this.logger.warn('Could not update file label:', error.message);
    }
  }
 
  /**
   * Shorten a file path for display in the UI
   * @param {string} path - The full path
   * @returns {string} The shortened path
   */
  shortenPath(path) {
    if (!path) {
      return '';
    }
    const maxLength = 30;
    if (path.length <= maxLength) {
      return path;
    }
 
    // Try to keep the most relevant parts
    const parts = path.split('/');
    if (parts.length <= 2) {
      return path.length > maxLength ? '...' + path.slice(-maxLength + 3) : path;
    }
 
    // Keep first and last parts, add ellipsis in middle
    const firstPart = parts[0];
    const lastPart = parts[parts.length - 1];
    const middleParts = parts.slice(1, -1);
    let result = firstPart;
    if (middleParts.length > 0) {
      result += '/.../' + lastPart;
    } else {
      result += '/' + lastPart;
    }
    return result.length > maxLength ? '...' + result.slice(-maxLength + 3) : result;
  }
 
  /**
   * Save file info to localStorage
   * @param {Object} fileInfo - File information object
   */
  saveFileInfo(fileInfo) {
    if (!fileInfo) {
      return;
    }
    try {
      const fileData = {
        name: fileInfo.name,
        size: fileInfo.size,
        lastModified: fileInfo.lastModified,
        type: fileInfo.type
      };
      localStorage.setItem('lastSelectedFile', JSON.stringify(fileData));
      this.lastFileInfo = fileData;
    } catch (error) {
      this.logger.error('Error saving file info:', error);
    }
  }
 
  /**
   * Clear file info from localStorage
   */
  clearFileInfo() {
    try {
      localStorage.removeItem('lastSelectedFile');
      this.lastFileInfo = null;
      if (this.fileInfo) {
        this.fileInfo.innerHTML = 'No file selected';
      }
    } catch (error) {
      this.logger.error('Error clearing file info:', error);
    }
  }
 
  /**
   * Clear the last folder path
   */
  clearLastFolderPath() {
    try {
      localStorage.removeItem('lastFolderPath');
      this.updateFileLabel();
      this.logger.info('Cleared last folder path');
    } catch (error) {
      this.logger.warn('Could not clear last folder path:', error.message);
    }
  }
 
  // ======================
  // File Handling
  // ======================
 
  /**
   * Initialize file input event listeners
   */
  initializeFileInput() {
    if (!this.fileInput) {
      return;
    }
 
    // Remove existing event listeners
    const newFileInput = this.fileInput.cloneNode(true);
    this.fileInput.parentNode.replaceChild(newFileInput, this.fileInput);
    this.fileInput = newFileInput;
 
    // Add new event listener
    this.fileInput.addEventListener('change', event => this.handleFileSelect(event));
 
    // Update file label to show last folder path if available
    this.updateFileLabel();
  }
 
  /**
   * Handle a File object directly (not an event)
   * @param {File} file - The file to handle
   */
  async handleFileObject(file) {
    if (!file) {
      throw new Error('File is required for handleFileObject');
    }
    await this._handleFileInternal(file);
  }
 
  /**
   * Handle file selection from an input event
   * @param {Event} event - The file selection event
   */
  async handleFileSelect(event) {
    if (!event || !event.target) {
      this.logger.warn('Invalid file selection event');
      return;
    }
    const file = event.target.files[0];
    if (!file) {
      this.logger.warn('No file selected');
      return;
    }
 
    // Save the folder path for next time
    this.saveLastFolderPath(file, 'import');
    await this._handleFileInternal(file, event);
  }
 
  /**
   * Shared internal file handling logic
   * @param {File} file - The file to process
   * @param {Event} [event] - The file selection event (optional)
   * @param {string} operationType - The operation type ('import', 'delete', 'modify')
   * @private
   */
  async _handleFileInternal(file, event) {
    let operationType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'import';
    if (!file) {
      throw new Error('File is required for internal file handling');
    }
    console.log('[CSV] _handleFileInternal called with file:', file.name, 'size:', file.size, 'operationType:', operationType);
    try {
      this.logger.info('Processing file', {
        fileName: file.name,
        fileSize: file.size,
        operationType
      });
 
      // Validate file type - allow files without extensions or with any extension except known bad ones
      const fileName = file.name || '';
      const fileExt = this.getFileExtension(fileName).toLowerCase();
      const knownBadExts = ['exe', 'js', 'png', 'jpg', 'jpeg', 'gif', 'pdf', 'zip', 'tar', 'gz'];
      if (fileExt && knownBadExts.includes(fileExt)) {
        const errorMsg = `Unsupported file type: ${fileExt}. Please upload a CSV or text file.`;
        this.logger.error(errorMsg, {
          fileName,
          fileExt
        });
        throw new Error(errorMsg);
      }
      // Accept all other extensions and blank/unknown types (including files with no extension)
 
      // Validate file size (10MB limit)
      const maxSize = 10 * 1024 * 1024; // 10MB
      if (file.size > maxSize) {
        throw new Error('File too large. Please select a file smaller than 10MB.');
      }
 
      // Read file content
      const content = await this.readFileAsText(file);
      console.log('[CSV] _handleFileInternal: About to parse CSV content, length:', content.length);
      // Parse CSV with enhanced validation
      const parseResults = this.parseCSV(content);
      console.log('[CSV] _handleFileInternal: parseCSV completed, parseResults:', parseResults);
 
      // Store parsed users
      this.parsedUsers = parseResults.users;
      this.lastParsedUsers = [...parseResults.users];
 
      // Update validation results for getTotalUsers() method
      this.validationResults = {
        total: parseResults.users.length,
        valid: parseResults.validUsers || parseResults.users.length,
        errors: parseResults.errors.length,
        warnings: parseResults.warnings.length
      };
 
      // Add debug logging
      console.log('[CSV] File parsed successfully:', {
        totalUsers: this.validationResults.total,
        validUsers: this.validationResults.valid,
        errors: this.validationResults.errors,
        warnings: this.validationResults.warnings
      });
 
      // Update UI with results
      const message = `File processed: ${parseResults.validUsers} valid users, ${parseResults.invalidRows} invalid rows`;
      this.uiManager.showNotification(message, parseResults.invalidRows > 0 ? 'warning' : 'success');
 
      // Update UI with enhanced file info display based on operation type
      const fileInfoContainerId = operationType === 'modify' ? 'modify-file-info' : 'file-info';
      this.updateFileInfoForElement(file, fileInfoContainerId, parseResults.validUsers);
 
      // Update file label to show last folder path
      this.updateFileLabel(operationType);
 
      // Log detailed errors for debugging
      if (parseResults.errors.length > 0) {
        this.logger.warn('CSV parsing errors', {
          errorCount: parseResults.errors.length,
          errors: parseResults.errors.slice(0, 10) // Log first 10 errors
        });
      }
 
      // Update button state based on operation type
      if (window.app) {
        if (operationType === 'modify' && window.app.updateModifyButtonState) {
          window.app.updateModifyButtonState();
        } else if (operationType === 'import' && window.app.updateImportButtonState) {
          window.app.updateImportButtonState();
        }
      }
    } catch (error) {
      this.logger.error('Failed to process CSV file', {
        error: error.message,
        fileName: file.name,
        operationType
      });
      console.error('Error in _handleFileInternal:', error);
      let errorMessage = 'Failed to process CSV file. ';
      if (error.message.includes('Missing required headers')) {
        errorMessage = `CSV file is missing required columns. ${error.message} Please ensure your CSV file has a 'username' column.`;
      } else if (error.message.includes('Invalid file type')) {
        errorMessage += 'Please select a valid CSV file.';
      } else if (error.message.includes('File too large')) {
        errorMessage += 'Please select a smaller file (max 10MB).';
      } else {
        errorMessage += error.message;
      }
      this.uiManager.showNotification(errorMessage, 'error');
 
      // Clear file input
      if (event && event.target && event.target.value) {
        event.target.value = '';
      }
    }
  }
 
  /**
   * Process a CSV file for user import
   * 
   * Validates the file format, reads its contents, parses CSV data,
   * and prepares user objects for import. Handles file validation,
   * CSV parsing, and error reporting.
   * 
   * @param {File} file - The CSV file to process
   * @returns {Promise<Object>} Promise that resolves with parsing results
   */
  async processCSV(file) {
    // Log file object for debugging
    this.logger.log('Processing file object:', 'debug', file);
 
    // Validate file exists and is not empty
    if (!file) {
      this.logger.error('No file provided to processCSV');
      throw new Error('No file selected');
    }
    if (file.size === 0) {
      this.logger.error('Empty file provided', {
        fileName: file.name,
        size: file.size
      });
      throw new Error('File is empty');
    }
 
    // Only block known bad extensions, allow all others
    const fileName = file.name || '';
    const fileExt = this.getFileExtension(fileName).toLowerCase();
    const knownBadExts = ['exe', 'js', 'png', 'jpg', 'jpeg', 'gif', 'pdf', 'zip', 'tar', 'gz'];
    if (fileExt && knownBadExts.includes(fileExt)) {
      const errorMsg = `Unsupported file type: ${fileExt}. Please upload a CSV or text file.`;
      this.logger.error(errorMsg, {
        fileName,
        fileExt
      });
      throw new Error(errorMsg);
    }
    // Accept all other extensions and blank/unknown types
    // Check file size (max 10MB)
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      throw new Error(`File is too large. Maximum size is ${this.formatFileSize(maxSize)}`);
    }
 
    // Update UI
    this.saveFileInfo(file);
    this.updateFileInfo(file);
 
    // Store the current file reference
    this.currentFile = file;
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = event => {
        try {
          const text = event.target.result;
          if (!text || text.trim() === '') {
            throw new Error('File is empty or contains no text');
          }
          console.log('[CSV] About to parse CSV text, length:', text.length);
          const {
            headers,
            rows
          } = this.parseCSV(text);
          console.log('[CSV] parseCSV completed, headers:', headers, 'rows count:', rows.length);
 
          // Validate required fields
          const missingHeaders = this.requiredFields.filter(field => !headers.includes(field));
          if (missingHeaders.length > 0) {
            throw new Error(`Missing required columns: ${missingHeaders.join(', ')}`);
          }
 
          // Convert rows to user objects and store them
          this.lastParsedUsers = rows.map(row => {
            const user = {};
            headers.forEach((header, index) => {
              user[header] = row[header] || '';
            });
            return user;
          });
 
          // Also store in parsedUsers for compatibility with getParsedUsers
          this.parsedUsers = this.lastParsedUsers;
 
          // Update validation results for getTotalUsers() method
          this.validationResults = {
            total: this.lastParsedUsers.length,
            valid: this.lastParsedUsers.length,
            errors: 0,
            warnings: 0
          };
 
          // Add debug logging
          console.log('[CSV] File parsed successfully (processCSV):', {
            totalUsers: this.validationResults.total,
            validUsers: this.validationResults.valid,
            errors: this.validationResults.errors,
            warnings: this.validationResults.warnings
          });
          resolve({
            success: true,
            headers,
            rows: this.lastParsedUsers,
            userCount: this.lastParsedUsers.length
          });
        } catch (error) {
          reject(error);
        }
      };
      reader.onerror = () => {
        reject(new Error('Error reading file'));
      };
      reader.readAsText(file);
    });
  }
 
  // ======================
  // CSV Parsing Methods
  // ======================
 
  /**
   * Parse CSV content into headers and data rows
   * 
   * Splits CSV content into lines, extracts headers, and validates
   * required and recommended columns. Handles header mapping for
   * different naming conventions.
   * 
   * @param {string} content - Raw CSV content as string
   * @returns {Object} Object containing headers and parsed rows
   */
  parseCSV(content) {
    // Split content into lines and filter out empty lines
    const lines = content.split('\n').filter(line => line.trim());
    if (lines.length < 2) {
      throw new Error('CSV file must have at least a header row and one data row');
    }
 
    // Parse headers from first line
    const headers = this.parseCSVLine(lines[0]);
 
    // Define required and recommended headers for validation
    const requiredHeaders = ['username'];
    const recommendedHeaders = ['firstName', 'lastName', 'email'];
 
    // Log all headers for debugging
    console.log('[CSV] All headers:', headers);
    console.log('[CSV] Required headers:', requiredHeaders);
    console.log('[CSV] Recommended headers:', recommendedHeaders);
 
    // Validate headers
    const missingRequired = requiredHeaders.filter(h => {
      const hasHeader = headers.some(header => {
        const headerLower = header.toLowerCase();
        const mappedHeader = this.getHeaderMapping(headerLower);
        const matches = headerLower === h.toLowerCase() || mappedHeader === h;
        console.log(`[CSV] Checking header "${header}" (${headerLower}) -> "${mappedHeader}" for required "${h}": ${matches}`);
        return matches;
      });
      console.log(`[CSV] Required header "${h}" found: ${hasHeader}`);
      return !hasHeader;
    });
    const missingRecommended = recommendedHeaders.filter(h => {
      const hasHeader = headers.some(header => {
        const headerLower = header.toLowerCase();
        const mappedHeader = this.getHeaderMapping(headerLower);
        const matches = headerLower === h.toLowerCase() || mappedHeader === h;
        console.log(`[CSV] Checking header "${header}" (${headerLower}) -> "${mappedHeader}" for recommended "${h}": ${matches}`);
        return matches;
      });
      console.log(`[CSV] Recommended header "${h}" found: ${hasHeader}`);
      return !hasHeader;
    });
    if (missingRequired.length > 0) {
      const errorMsg = `Missing required headers: ${missingRequired.join(', ')}. At minimum, you need a 'username' column.`;
      this.logger.error('CSV validation failed - missing required headers', {
        missingRequired,
        availableHeaders: headers,
        errorMsg
      });
      throw new Error(errorMsg);
    }
    if (missingRecommended.length > 0) {
      const warningMsg = `Missing recommended headers: ${missingRecommended.join(', ')}. These are not required but recommended for better user data.`;
      this.logger.warn('CSV validation warning - missing recommended headers', {
        missingRecommended,
        availableHeaders: headers,
        warningMsg
      });
      // Show warning but don't throw error
      if (window.app && window.app.uiManager) {
        window.app.uiManager.showNotification(warningMsg, 'warning');
      }
    }
    const users = [];
    const errors = [];
    const warnings = [];
    let rowNumber = 1; // Start from 1 since 0 is header
 
    for (let i = 1; i < lines.length; i++) {
      rowNumber = i + 1; // +1 because we start from header row
      const line = lines[i].trim();
      if (!line) continue; // Skip empty lines
 
      try {
        const user = this.parseUserRow(line, headers, rowNumber);
 
        // Validate user data
        const validationResult = this.validateUserData(user, rowNumber);
        if (validationResult.isValid) {
          users.push(user);
        } else {
          errors.push({
            row: rowNumber,
            user: user,
            errors: validationResult.errors,
            warnings: validationResult.warnings
          });
 
          // Add warnings to warnings array
          warnings.push(...validationResult.warnings.map(w => ({
            row: rowNumber,
            ...w
          })));
        }
      } catch (error) {
        errors.push({
          row: rowNumber,
          error: error.message,
          line: line
        });
      }
    }
 
    // Log comprehensive validation results
    const validationSummary = {
      totalRows: lines.length - 1,
      validUsers: users.length,
      invalidRows: errors.length,
      warnings: warnings.length,
      missingRequiredHeaders: missingRequired,
      missingRecommendedHeaders: missingRecommended,
      availableHeaders: headers
    };
    this.logger.info('CSV parsing completed', validationSummary);
    if (errors.length > 0) {
      const errorDetails = errors.map(e => ({
        row: e.row,
        errors: e.errors || [e.error],
        warnings: e.warnings || []
      }));
      this.logger.warn('CSV validation issues found', {
        totalErrors: errors.length,
        errorDetails: errorDetails.slice(0, 10) // Log first 10 errors
      });
    }
 
    // Show user-friendly summary
    this.showValidationSummary(validationSummary, errors, warnings);
    return {
      users,
      errors,
      warnings,
      totalRows: lines.length - 1,
      validUsers: users.length,
      invalidRows: errors.length,
      headerCount: headers.length,
      availableHeaders: headers
    };
  }
 
  /**
   * Parse a single CSV line
   * @param {string} line - CSV line to parse
   * @param {string} delimiter - Delimiter character
   * @returns {Array<string>} Array of field values
   */
  parseCSVLine(line) {
    let delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
    const result = [];
    let current = '';
    let inQuotes = false;
    for (let i = 0; i < line.length; i++) {
      const char = line[i];
      const nextChar = line[i + 1];
      if (char === '"') {
        if (nextChar === '"') {
          current += '"';
          i++;
        } else {
          inQuotes = !inQuotes;
        }
      } else if (char === delimiter && !inQuotes) {
        result.push(current);
        current = '';
      } else {
        current += char;
      }
    }
    result.push(current);
    return result.map(field => field.trim());
  }
 
  /**
   * Parse a user row from CSV
   * @param {string} line - CSV line to parse
   * @param {Array<string>} headers - Header row
   * @param {number} rowNumber - Row number for error reporting
   * @returns {Object} Parsed user object
   */
  parseUserRow(line, headers, rowNumber) {
    const values = this.parseCSVLine(line);
    if (values.length !== headers.length) {
      throw new Error(`Row ${rowNumber}: Number of columns (${values.length}) doesn't match headers (${headers.length})`);
    }
    const user = {};
    for (let i = 0; i < headers.length; i++) {
      const header = headers[i].toLowerCase().trim();
      let value = values[i].trim();
 
      // Handle boolean values
      if (header === 'enabled') {
        const valueLower = value.toLowerCase();
        if (valueLower === 'true' || value === '1') {
          value = true;
        } else if (valueLower === 'false' || value === '0') {
          value = false;
        } else if (value === '') {
          value = true; // Default to enabled
        } else {
          throw new Error(`Row ${rowNumber}: Invalid enabled value '${value}'. Must be true/false or 1/0`);
        }
      }
 
      // Map common header variations
      const mappedHeader = this.getHeaderMapping(header);
      console.log(`[CSV] Mapping header: "${header}" -> "${mappedHeader}"`);
      user[mappedHeader] = value;
    }
 
    // Set default username if not provided
    if (!user.username && user.email) {
      user.username = user.email;
    }
    return user;
  }
 
  /**
   * Validate user data for a specific row
   * @param {Object} user - User object to validate
   * @param {number} rowNumber - Row number for error reporting
   * @returns {Object} Validation result with isValid, errors, and warnings
   */
  validateUserData(user, rowNumber) {
    const errors = [];
    const warnings = [];
 
    // Check required fields
    if (!user.username || user.username.trim() === '') {
      errors.push('Username is required and cannot be empty');
    }
 
    // Check recommended fields
    if (!user.firstName || user.firstName.trim() === '') {
      warnings.push('firstName is recommended for better user data');
    }
    if (!user.lastName || user.lastName.trim() === '') {
      warnings.push('lastName is recommended for better user data');
    }
    if (!user.email || user.email.trim() === '') {
      warnings.push('email is recommended for better user data');
    }
 
    // Validate email format if provided
    if (user.email && user.email.trim() !== '' && !this.isValidEmail(user.email)) {
      errors.push('Invalid email format');
    }
 
    // Validate username format if provided
    if (user.username && !this.isValidUsername(user.username)) {
      errors.push('Username contains invalid characters (no spaces or special characters allowed)');
    }
    return {
      isValid: errors.length === 0,
      errors,
      warnings
    };
  }
 
  /**
   * Show validation summary to user
   * @param {Object} summary - Validation summary
   * @param {Array} errors - Array of errors
   * @param {Array} warnings - Array of warnings
   */
  showValidationSummary(summary, errors, warnings) {
    let message = '';
    let type = 'success';
    if (summary.invalidRows > 0) {
      type = 'error';
      message = `File validation failed!\n\n`;
      message += `• Total rows: ${summary.totalRows}\n`;
      message += `• Valid users: ${summary.validUsers}\n`;
      message += `• Invalid rows: ${summary.invalidRows}\n`;
      message += `• Warnings: ${warnings.length}\n\n`;
      if (summary.missingRequiredHeaders.length > 0) {
        message += `❌ Missing required headers: ${summary.missingRequiredHeaders.join(', ')}\n`;
      }
      if (errors.length > 0) {
        message += `❌ Data errors found in ${errors.length} row(s)\n`;
        // Show first few specific errors
        const firstErrors = errors.slice(0, 3);
        firstErrors.forEach(error => {
          if (error.errors) {
            message += `  Row ${error.row}: ${error.errors.join(', ')}\n`;
          } else if (error.error) {
            message += `  Row ${error.row}: ${error.error}\n`;
          }
        });
        if (errors.length > 3) {
          message += `  ... and ${errors.length - 3} more errors\n`;
        }
      }
    } else if (warnings.length > 0) {
      type = 'warning';
      message = `File loaded with warnings:\n\n`;
      message += `• Total rows: ${summary.totalRows}\n`;
      message += `• Valid users: ${summary.validUsers}\n`;
      message += `• Warnings: ${warnings.length}\n\n`;
      if (summary.missingRecommendedHeaders.length > 0) {
        message += `⚠️ Missing recommended headers: ${summary.missingRecommendedHeaders.join(', ')}\n`;
      }
 
      // Show first few warnings
      const firstWarnings = warnings.slice(0, 3);
      firstWarnings.forEach(warning => {
        message += `  Row ${warning.row}: ${warning.message || warning}\n`;
      });
      if (warnings.length > 3) {
        message += `  ... and ${warnings.length - 3} more warnings\n`;
      }
    } else {
      message = `File loaded successfully!\n\n`;
      message += `• Total rows: ${summary.totalRows}\n`;
      message += `• Valid users: ${summary.validUsers}\n`;
      message += `• Headers found: ${summary.availableHeaders.join(', ')}`;
    }
 
    // Show notification to user
    if (window.app && window.app.uiManager) {
      window.app.uiManager.showNotification(message, type);
    }
 
    // Log to server
    this.logger.info('CSV validation summary shown to user', {
      summary,
      message,
      type
    });
  }
 
  /**
   * Get header mapping for common variations
   * @param {string} header - Header to map
   * @returns {string} Mapped header name
   */
  getHeaderMapping(header) {
    const headerMap = {
      'firstname': 'firstName',
      'first_name': 'firstName',
      'givenname': 'firstName',
      'given_name': 'firstName',
      'lastname': 'lastName',
      'last_name': 'lastName',
      'familyname': 'lastName',
      'family_name': 'lastName',
      'surname': 'lastName',
      'emailaddress': 'email',
      'email_address': 'email',
      'userid': 'username',
      'user_id': 'username',
      'login': 'username',
      'user': 'username',
      'populationid': 'populationId',
      'population_id': 'populationId',
      'popid': 'populationId',
      'pop_id': 'populationId'
    };
    return headerMap[header] || header;
  }
 
  /**
   * Check if email is valid
   * @param {string} email - Email to validate
   * @returns {boolean} True if valid
   */
  isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }
 
  /**
   * Check if username is valid
   * @param {string} username - Username to validate
   * @returns {boolean} True if valid
   */
  isValidUsername(username) {
    // Username should not contain spaces or special characters
    const usernameRegex = /^[a-zA-Z0-9._-]+$/;
    return usernameRegex.test(username);
  }
 
  // ======================
  // UI Updates
  // ======================
 
  /**
   * Update file info for any file info container element
   * @param {File} file - The file object
   * @param {string} containerId - The ID of the container element to update
   */
  updateFileInfoForElement(file, containerId) {
    let recordCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    const container = document.getElementById(containerId);
    console.log('updateFileInfoForElement called:', {
      containerId,
      container: !!container,
      file: !!file,
      recordCount
    });
    if (!container || !file) {
      console.warn('updateFileInfoForElement: container or file is null', {
        containerId,
        hasContainer: !!container,
        hasFile: !!file
      });
      return;
    }
    const fileSize = this.formatFileSize(file.size);
    const lastModified = new Date(file.lastModified).toLocaleString();
    const fileType = file.type || this.getFileExtension(file.name);
    const fileExtension = this.getFileExtension(file.name);
 
    // Get file path information (if available)
    let filePath = 'Unknown';
    if (file.webkitRelativePath) {
      filePath = file.webkitRelativePath;
    } else if (file.name) {
      // Try to extract directory from file name if it contains path separators
      const pathParts = file.name.split(/[\/\\]/);
      if (pathParts.length > 1) {
        filePath = pathParts.slice(0, -1).join('/');
      } else {
        filePath = 'Current Directory';
      }
    }
 
    // Calculate additional file properties
    const isCSV = fileExtension === 'csv';
    const isText = fileExtension === 'txt';
    const isValidType = isCSV || isText || fileType === 'text/csv' || fileType === 'text/plain';
    const fileSizeInKB = Math.round(file.size / 1024);
    const fileSizeInMB = Math.round(file.size / 1024 / 1024 * 100) / 100;
 
    // Determine record count display
    let recordCountHTML = '';
    if (isValidType && recordCount !== null) {
      if (typeof recordCount === 'number') {
        if (recordCount > 0) {
          recordCountHTML = `<div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;"><strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">🧾 Records</strong><span style="color: #0073C8; font-size: 0.8rem; font-weight: bold;">${recordCount}</span></div>`;
        } else {
          recordCountHTML = `<div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;"><strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">🧾 Records</strong><span style="color: #dc3545; font-size: 0.8rem; font-weight: bold;">No user records found</span></div>`;
        }
      }
    }
 
    // Create compact file info display with reduced footprint
    const fileInfoHTML = `
            <div class="file-info-details" style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 6px; padding: 12px; margin: 8px 0; box-shadow: 0 1px 4px rgba(0,0,0,0.08);">
                
                <!-- Compact File Name Section -->
                <div class="file-name-section" style="text-align: center; margin-bottom: 12px; padding: 8px; background: #e6f4ff; border-radius: 4px; color: #1a237e; font-weight: bold; font-size: 1.1rem;">
                    <div style="font-size: 1.3rem; font-weight: 600; margin-bottom: 3px; color: #1a237e; text-shadow: none; word-break: break-word; overflow-wrap: break-word;">
                        <i class="fas fa-file-csv" style="margin-right: 6px; font-size: 1.2rem; color: #1976d2;"></i>
                        ${file.name}
                    </div>
                    <div style="font-size: 0.85rem; opacity: 0.9; font-weight: 500; color: #1976d2;">
                        File Selected Successfully
                    </div>
                </div>
                
                <!-- Compact File Information Grid -->
                <div class="file-info-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; font-size: 0.8em; margin-bottom: 10px;">
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">📊 File Size</strong>
                        <span style="color: #6c757d; font-size: 0.8rem;">${fileSize} (${fileSizeInKB} KB, ${fileSizeInMB} MB)</span>
                    </div>
                    
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">📂 Directory</strong>
                        <span style="color: #6c757d; word-break: break-all; font-size: 0.8rem;">${filePath}</span>
                    </div>
                    
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">📅 Last Modified</strong>
                        <span style="color: #6c757d; font-size: 0.8rem;">${lastModified}</span>
                    </div>
                    
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">🔤 File Type</strong>
                        <span style="color: #6c757d; font-size: 0.8rem;">${fileType || 'Unknown'}</span>
                    </div>
                    
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">📄 Extension</strong>
                        <span style="color: ${isValidType ? '#28a745' : '#dc3545'}; font-weight: bold; font-size: 0.8rem;">
                            ${fileExtension ? '.' + fileExtension : 'None'}
                        </span>
                    </div>
                    ${recordCountHTML}
                </div>
                
                <!-- Compact File Status Section -->
                <div class="file-info-status" style="margin-top: 8px; padding: 8px; border-radius: 4px; background: ${isValidType ? '#d4edda' : '#f8d7da'}; border: 1px solid ${isValidType ? '#c3e6cb' : '#f5c6cb'}; display: flex; align-items: center; gap: 6px;">
                    <i class="fas ${isValidType ? 'fa-check-circle' : 'fa-exclamation-triangle'}" style="color: ${isValidType ? '#155724' : '#721c24'}; font-size: 1rem;"></i>
                    <span style="color: ${isValidType ? '#155724' : '#721c24'}; font-weight: bold; font-size: 0.85rem;">
                        ${isValidType ? '✅ File type is supported and ready for processing' : '⚠️ Warning: File type may not be optimal for import'}
                    </span>
                </div>
                
                ${file.size > 5 * 1024 * 1024 ? `
                <div class="file-info-warning" style="margin-top: 8px; padding: 8px; border-radius: 4px; background: #fff3cd; border: 1px solid #ffeaa7; display: flex; align-items: center; gap: 6px;">
                    <i class="fas fa-exclamation-triangle" style="color: #856404; font-size: 1rem;"></i>
                    <span style="color: #856404; font-weight: bold; font-size: 0.85rem;">Large file detected - processing may take longer than usual</span>
                </div>
                ` : ''}
                
                <!-- Responsive Design -->
                <style>
                    @media (max-width: 768px) {
                        .file-info-details .file-name-section div:first-child {
                            font-size: 1.1rem !important;
                        }
                        .file-info-grid {
                            grid-template-columns: 1fr !important;
                            gap: 6px !important;
                        }
                        .file-info-item {
                            padding: 6px !important;
                        }
                    }
                    @media (max-width: 480px) {
                        .file-info-details .file-name-section div:first-child {
                            font-size: 0.95rem !important;
                        }
                        .file-info-details {
                            padding: 8px !important;
                        }
                    }
                </style>
            </div>
        `;
    container.innerHTML = fileInfoHTML;
  }
  updateFileInfo(file) {
    let recordCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    this.updateFileInfoForElement(file, 'file-info', recordCount);
  }
  showPreview(rows) {
    if (!this.previewContainer) return;
    if (!rows || rows.length === 0) {
      this.previewContainer.innerHTML = '<div class="alert alert-info">No data to display</div>';
      // Disable import button if no rows
      const importBtnBottom = _elementRegistry.ElementRegistry.startImportBtnBottom ? _elementRegistry.ElementRegistry.startImportBtnBottom() : null;
      if (importBtnBottom) {
        importBtnBottom.disabled = true;
      }
      return;
    }
    const headers = Object.keys(rows[0]);
    const previewRows = rows.slice(0, 5); // Show first 5 rows
 
    let html = `
            <div class="table-responsive">
                <table class="table table-sm table-striped">
                    <thead>
                        <tr>
                            ${headers.map(h => `<th>${h}</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody>
                        ${previewRows.map(row => `
                            <tr>
                                ${headers.map(h => `<td>${row[h] || ''}</td>`).join('')}
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
                ${rows.length > 5 ? `<small class="text-muted">Showing 5 of ${rows.length} rows</small>` : ''}
            </div>
        `;
    this.previewContainer.innerHTML = html;
 
    // Check if population choice has been made
    const hasPopulationChoice = this.checkPopulationChoice();
 
    // Enable import button after showing preview (only if population choice is made)
    const importBtnBottom = _elementRegistry.ElementRegistry.startImportBtnBottom ? _elementRegistry.ElementRegistry.startImportBtnBottom() : null;
    if (importBtnBottom) {
      importBtnBottom.disabled = !hasPopulationChoice;
      this.logger.log(`Import button ${hasPopulationChoice ? 'enabled' : 'disabled'}`, 'debug');
    } else {
      this.logger.warn('Could not find import button to enable', 'warn');
    }
  }
 
  /**
   * Check if user has made a population choice
   * @returns {boolean} True if a population choice has been made
   */
  checkPopulationChoice() {
    const selectedPopulationId = _elementRegistry.ElementRegistry.importPopulationSelect ? _elementRegistry.ElementRegistry.importPopulationSelect().value || '' : '';
    const useDefaultPopulation = _elementRegistry.ElementRegistry.useDefaultPopulationCheckbox ? _elementRegistry.ElementRegistry.useDefaultPopulationCheckbox().checked || false : false;
    const useCsvPopulationId = _elementRegistry.ElementRegistry.useCsvPopulationIdCheckbox ? _elementRegistry.ElementRegistry.useCsvPopulationIdCheckbox().checked || false : false;
    const hasSelectedPopulation = selectedPopulationId && selectedPopulationId.trim() !== '';
    return hasSelectedPopulation || useDefaultPopulation || useCsvPopulationId;
  }
 
  // ======================
  // Utility Methods
  // ======================
 
  getFileExtension(filename) {
    if (!filename || typeof filename !== 'string') return '';
 
    // Handle cases where filename might be a path
    const lastDot = filename.lastIndexOf('.');
    const lastSlash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
 
    // If there's no dot, or the dot is before the last slash, return empty string
    if (lastDot === -1 || lastSlash > lastDot) return '';
 
    // Extract and return the extension (without the dot)
    return filename.slice(lastDot + 1).toLowerCase().trim();
  }
  formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
  generateTemporaryPassword() {
    const length = 16;
    const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+~`|}{[]\\:;?><,./-';
    let password = '';
 
    // Ensure at least one of each character type
    password += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[Math.floor(Math.random() * 26)];
    password += 'abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 26)];
    password += '0123456789'[Math.floor(Math.random() * 10)];
    password += '!@#$%^&*'[Math.floor(Math.random() * 8)];
 
    // Fill the rest of the password
    for (let i = password.length; i < length; i++) {
      password += charset[Math.floor(Math.random() * charset.length)];
    }
 
    // Shuffle the password
    return password.split('').sort(() => Math.random() - 0.5).join('');
  }
 
  /**
   * Get parsed users for import
   * @returns {Array<Object>} Array of validated user objects
   */
  getParsedUsers() {
    this.logger.info('getParsedUsers called', {
      hasParsedUsers: !!this.parsedUsers,
      parsedUsersType: typeof this.parsedUsers,
      parsedUsersLength: this.parsedUsers ? this.parsedUsers.length : 0,
      hasLastParsedUsers: !!this.lastParsedUsers,
      lastParsedUsersType: typeof this.lastParsedUsers,
      lastParsedUsersLength: this.lastParsedUsers ? this.lastParsedUsers.length : 0
    });
    if (!this.parsedUsers || !Array.isArray(this.parsedUsers)) {
      this.logger.warn('No parsed users available');
 
      // Show user-friendly notification
      if (this.uiManager && this.uiManager.showNotification) {
        this.uiManager.showNotification('No CSV file has been uploaded yet. Please upload a CSV file first.', 'info');
      }
      return [];
    }
    this.logger.info('Retrieving parsed users for import', {
      userCount: this.parsedUsers.length,
      hasUsers: this.parsedUsers.length > 0
    });
    return this.parsedUsers;
  }
 
  /**
   * Get parsing results for debugging
   * @returns {Object|null} Parsing results or null if not available
   */
  getParseResults() {
    return this.parseResults || null;
  }
 
  /**
   * Initialize drag-and-drop support for a drop zone element
   * @param {HTMLElement} dropZone - The drop zone element
   */
  initializeDropZone(dropZone) {
    if (!dropZone) return;
 
    // Remove any previous listeners
    dropZone.removeEventListener('dragenter', this._onDragEnter);
    dropZone.removeEventListener('dragover', this._onDragOver);
    dropZone.removeEventListener('dragleave', this._onDragLeave);
    dropZone.removeEventListener('drop', this._onDrop);
 
    // Bind event handlers to this instance
    this._onDragEnter = e => {
      e.preventDefault();
      e.stopPropagation();
      dropZone.classList.add('drag-over');
    };
    this._onDragOver = e => {
      e.preventDefault();
      e.stopPropagation();
      dropZone.classList.add('drag-over');
    };
    this._onDragLeave = e => {
      e.preventDefault();
      e.stopPropagation();
      dropZone.classList.remove('drag-over');
    };
    this._onDrop = async e => {
      e.preventDefault();
      e.stopPropagation();
      dropZone.classList.remove('drag-over');
      const files = e.dataTransfer.files;
      if (files && files.length > 0) {
        try {
          await this.setFile(files[0]);
        } catch (error) {
          this.logger.error('Drag-and-drop file error', {
            error: error.message
          });
          this.uiManager.showNotification('Failed to process dropped file: ' + error.message, 'error');
        }
      }
    };
 
    // Attach listeners
    dropZone.addEventListener('dragenter', this._onDragEnter);
    dropZone.addEventListener('dragover', this._onDragOver);
    dropZone.addEventListener('dragleave', this._onDragLeave);
    dropZone.addEventListener('drop', this._onDrop);
  }
 
  /**
   * Initialize global drag-and-drop prevention and routing
   * This prevents the browser from trying to open files and routes them to the app
   */
  initializeGlobalDragAndDrop() {
    // Prevent browser default behavior for file drops anywhere on the page
    const preventDefaultDragEvents = e => {
      e.preventDefault();
      e.stopPropagation();
    };
 
    // Handle file drops anywhere on the document
    const handleGlobalDrop = async e => {
      e.preventDefault();
      e.stopPropagation();
 
      // Remove body drag-over class
      document.body.classList.remove('drag-over');
      const files = e.dataTransfer.files;
      if (files && files.length > 0) {
        const file = files[0];
 
        // Check if it's a supported file type
        const fileName = file.name || '';
        const fileExt = this.getFileExtension(fileName).toLowerCase();
        const supportedExts = ['csv', 'txt'];
        const knownBadExts = ['exe', 'js', 'png', 'jpg', 'jpeg', 'gif', 'pdf', 'zip', 'tar', 'gz'];
        if (fileExt && knownBadExts.includes(fileExt)) {
          this.uiManager.showNotification(`Unsupported file type: ${fileExt}. Please upload a CSV or text file.`, 'error');
          return;
        }
 
        // Route to appropriate handler based on current view
        const currentView = this.getCurrentView();
        let targetDropZone = null;
        switch (currentView) {
          case 'import':
            targetDropZone = document.getElementById('import-drop-zone');
            break;
          case 'modify':
            targetDropZone = document.getElementById('modify-drop-zone');
            break;
          case 'import-dashboard':
            targetDropZone = document.getElementById('upload-zone');
            break;
          default:
            // Default to import view if no specific view is active
            targetDropZone = document.getElementById('import-drop-zone');
            break;
        }
 
        // Show visual feedback on the target drop zone
        if (targetDropZone) {
          targetDropZone.classList.add('drag-over');
          setTimeout(() => {
            targetDropZone.classList.remove('drag-over');
          }, 2000);
        }
        try {
          await this.setFile(file);
          this.uiManager.showNotification(`File "${file.name}" processed successfully`, 'success');
        } catch (error) {
          this.logger.error('Global drag-and-drop file error', {
            error: error.message
          });
          this.uiManager.showNotification('Failed to process dropped file: ' + error.message, 'error');
        }
      }
    };
 
    // Add visual feedback when dragging files over the document
    const handleGlobalDragEnter = e => {
      e.preventDefault();
      e.stopPropagation();
 
      // Only add visual feedback if dragging files
      if (e.dataTransfer.types.includes('Files')) {
        document.body.classList.add('drag-over');
      }
    };
    const handleGlobalDragLeave = e => {
      e.preventDefault();
      e.stopPropagation();
 
      // Only remove visual feedback if leaving the document entirely
      if (e.target === document || e.target === document.body) {
        document.body.classList.remove('drag-over');
      }
    };
 
    // Add global event listeners
    document.addEventListener('dragover', preventDefaultDragEvents);
    document.addEventListener('dragenter', handleGlobalDragEnter);
    document.addEventListener('dragleave', handleGlobalDragLeave);
    document.addEventListener('drop', handleGlobalDrop);
 
    // Store references for cleanup
    this._globalDragHandlers = {
      preventDefaultDragEvents,
      handleGlobalDragEnter,
      handleGlobalDragLeave,
      handleGlobalDrop
    };
    this.logger.info('Global drag-and-drop prevention initialized');
  }
 
  /**
   * Clean up global drag-and-drop event listeners
   */
  cleanupGlobalDragAndDrop() {
    if (this._globalDragHandlers) {
      document.removeEventListener('dragover', this._globalDragHandlers.preventDefaultDragEvents);
      document.removeEventListener('dragenter', this._globalDragHandlers.handleGlobalDragEnter);
      document.removeEventListener('dragleave', this._globalDragHandlers.handleGlobalDragLeave);
      document.removeEventListener('drop', this._globalDragHandlers.handleGlobalDrop);
      this._globalDragHandlers = null;
    }
 
    // Remove any remaining visual feedback
    document.body.classList.remove('drag-over');
  }
 
  /**
   * Get the current active view
   * @returns {string} The current view name
   */
  getCurrentView() {
    const activeView = document.querySelector('.view[style*="block"]') || document.querySelector('.view:not([style*="none"])');
    if (!activeView) return 'import';
    const viewId = activeView.id;
    if (viewId === 'import-dashboard-view') return 'import-dashboard';
    if (viewId === 'modify-csv-view') return 'modify';
    if (viewId === 'delete-csv-view') return 'delete';
    if (viewId === 'export-view') return 'export';
    if (viewId === 'settings-view') return 'settings';
    if (viewId === 'logs-view') return 'logs';
    return 'import'; // Default to import view
  }
}
exports.FileHandler = FileHandler;
 
},{"./element-registry.js":47}],51:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FileLogger = void 0;
/**
 * FileLogger - Handles writing logs to a client.log file using the File System Access API
 */
class FileLogger {
  /**
   * Create a new FileLogger instance
   * @param {string} filename - Name of the log file (default: 'client.log')
   */
  constructor() {
    let filename = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'client.log';
    this.filename = filename;
    this.fileHandle = null;
    this.writableStream = null;
    this.initialized = false;
    this.logQueue = [];
    this.initializationPromise = null;
  }
 
  /**
   * Initialize the file logger
   * @private
   */
  async _initialize() {
    if (this.initialized) return true;
    if (this.initializationPromise) {
      return this.initializationPromise;
    }
    this.initializationPromise = (async () => {
      try {
        // Check if we're in a secure context and the API is available
        if (!window.isSecureContext || !window.showSaveFilePicker) {
          throw new Error('File System Access API not available in this context');
        }
 
        // Only proceed if we're handling a user gesture
        if (!window.__fileLoggerUserGesture) {
          // Set up event listeners
          window.addEventListener('online', () => this.handleOnline());
          window.addEventListener('offline', () => this.handleOffline());
 
          // Set up user gesture detection for file logger
          const handleUserGesture = () => {
            window.__fileLoggerUserGesture = true;
            window.removeEventListener('click', handleUserGesture);
            window.removeEventListener('keydown', handleUserGesture);
 
            // Try to initialize the file logger if it hasn't been initialized yet
            if (this.fileLogger && !this.fileLogger._initialized && this.fileLogger._logger === null) {
              this.fileLogger._ensureInitialized().catch(console.warn);
            }
          };
          window.addEventListener('click', handleUserGesture, {
            once: true,
            passive: true
          });
          window.addEventListener('keydown', handleUserGesture, {
            once: true,
            passive: true
          });
          throw new Error('Waiting for user gesture to initialize file logger');
        }
        try {
          this.fileHandle = await window.showSaveFilePicker({
            suggestedName: this.filename,
            types: [{
              description: 'Log File',
              accept: {
                'text/plain': ['.log']
              }
            }],
            excludeAcceptAllOption: true
          });
          this.writableStream = await this.fileHandle.createWritable({
            keepExistingData: true
          });
          this.initialized = true;
          await this._processQueue();
          return true;
        } catch (error) {
          console.warn('File System Access API not available:', error);
          this.initialized = false;
          return false;
        }
      } catch (error) {
        console.warn('File logger initialization deferred:', error.message);
        this.initialized = false;
        return false;
      }
    })();
    return this.initializationPromise;
  }
 
  /**
   * Process any queued log messages
   * @private
   */
  async _processQueue() {
    if (this.logQueue.length === 0) return;
    const queue = [...this.logQueue];
    this.logQueue = [];
    for (const {
      level,
      message,
      timestamp
    } of queue) {
      await this._writeLog(level, message, timestamp);
    }
  }
 
  /**
   * Write a log message to the file
   * @private
   */
  async _writeLog(level, message, timestamp) {
    if (!this.initialized) {
      await this._initialize();
    }
    const logEntry = `[${timestamp}] [${level.toUpperCase()}] ${message}\n`;
    if (this.writableStream) {
      try {
        await this.writableStream.write(logEntry);
      } catch (error) {
        console.error('Error writing to log file:', error);
        this.initialized = false;
        await this._initialize();
        await this.writableStream.write(logEntry);
      }
    } else {
      console[level](`[FileLogger] ${logEntry}`);
    }
  }
 
  /**
   * Log a message
   * @param {string} level - Log level (info, warn, error, debug)
   * @param {string} message - The message to log
   */
  async log(level, message) {
    const timestamp = new Date().toISOString();
    if (!this.initialized) {
      this.logQueue.push({
        level,
        message,
        timestamp
      });
      await this._initialize();
    } else {
      await this._writeLog(level, message, timestamp);
    }
  }
 
  /**
   * Log an info message
   * @param {string} message - The message to log
   */
  info(message) {
    return this.log('info', message);
  }
 
  /**
   * Log a warning message
   * @param {string} message - The message to log
   */
  warn(message) {
    return this.log('warn', message);
  }
 
  /**
   * Log an error message
   * @param {string} message - The message to log
   */
  error(message) {
    return this.log('error', message);
  }
 
  /**
   * Log a debug message
   * @param {string} message - The message to log
   */
  debug(message) {
    return this.log('debug', message);
  }
 
  /**
   * Close the log file
   */
  async close() {
    if (this.writableStream) {
      try {
        await this.writableStream.close();
      } catch (error) {
        console.error('Error closing log file:', error);
      } finally {
        this.initialized = false;
        this.writableStream = null;
        this.fileHandle = null;
      }
    }
  }
}
exports.FileLogger = FileLogger;
 
},{}],52:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.HistorySubsystem = void 0;
/**
 * History Subsystem
 * Centralized history management system that replaces legacy HistoryManager
 * Provides operation history tracking, filtering, and event integration
 */
 
class HistorySubsystem {
  constructor(eventBus, settingsSubsystem, loggingSubsystem) {
    this.eventBus = eventBus;
    this.settingsSubsystem = settingsSubsystem;
    this.loggingSubsystem = loggingSubsystem;
 
    // History storage
    this.history = [];
    this.maxHistorySize = 500;
 
    // History categories
    this.categories = {
      IMPORT: 'import',
      EXPORT: 'export',
      DELETE: 'delete',
      MODIFY: 'modify',
      SETTINGS: 'settings',
      AUTH: 'auth',
      SYSTEM: 'system'
    };
 
    // History status types
    this.statusTypes = {
      STARTED: 'started',
      IN_PROGRESS: 'in_progress',
      COMPLETED: 'completed',
      FAILED: 'failed',
      CANCELLED: 'cancelled',
      PARTIAL: 'partial'
    };
 
    // Current filter settings
    this.currentFilter = {
      category: null,
      status: null,
      dateRange: null,
      search: null
    };
 
    // Initialize subsystem
    this.init();
    if (this.loggingSubsystem) {
      this.loggingSubsystem.info('HistorySubsystem initialized successfully', {}, 'system');
    }
  }
 
  /**
   * Initialize the history subsystem
   */
  async init() {
    try {
      // Load history settings
      await this.loadSettings();
 
      // Set up event listeners
      this.setupEventListeners();
 
      // Load existing history from storage
      await this.loadHistoryFromStorage();
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info('HistorySubsystem initialization complete', {
          historyCount: this.history.length
        }, 'system');
      }
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to initialize HistorySubsystem', error, 'system');
      }
      throw error;
    }
  }
 
  /**
   * Load history settings from SettingsSubsystem
   */
  async loadSettings() {
    try {
      if (this.settingsSubsystem) {
        // Access the current settings from the SettingsSubsystem
        // The SettingsSubsystem stores settings in currentSettings property
        const settings = this.settingsSubsystem.currentSettings;
 
        // Set max history size from settings
        if (settings && settings.maxHistorySize) {
          this.maxHistorySize = settings.maxHistorySize;
        }
      }
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.warn('Could not load history settings, using defaults', error, 'system');
      }
    }
  }
 
  /**
   * Set up event listeners for cross-subsystem communication
   */
  setupEventListeners() {
    if (this.eventBus) {
      // Listen for operation events to automatically track history
      this.eventBus.on('importStarted', data => {
        this.addHistoryEntry('import', 'Import operation started', 'started', data);
      });
      this.eventBus.on('importCompleted', data => {
        this.updateHistoryEntry(data.sessionId, 'completed', 'Import operation completed', data);
      });
      this.eventBus.on('importFailed', data => {
        this.updateHistoryEntry(data.sessionId, 'failed', 'Import operation failed', data);
      });
      this.eventBus.on('exportStarted', data => {
        this.addHistoryEntry('export', 'Export operation started', 'started', data);
      });
      this.eventBus.on('exportCompleted', data => {
        this.updateHistoryEntry(data.sessionId, 'completed', 'Export operation completed', data);
      });
      this.eventBus.on('exportFailed', data => {
        this.updateHistoryEntry(data.sessionId, 'failed', 'Export operation failed', data);
      });
      this.eventBus.on('deleteOperationStarted', data => {
        this.addHistoryEntry('delete', 'Delete operation started', 'started', data);
      });
      this.eventBus.on('deleteOperationCompleted', data => {
        this.updateHistoryEntry(data.sessionId, 'completed', 'Delete operation completed', data);
      });
      this.eventBus.on('deleteOperationFailed', data => {
        this.updateHistoryEntry(data.sessionId, 'failed', 'Delete operation failed', data);
      });
      this.eventBus.on('modifyOperationStarted', data => {
        this.addHistoryEntry('modify', 'Modify operation started', 'started', data);
      });
      this.eventBus.on('modifyOperationCompleted', data => {
        this.updateHistoryEntry(data.sessionId, 'completed', 'Modify operation completed', data);
      });
      this.eventBus.on('modifyOperationFailed', data => {
        this.updateHistoryEntry(data.sessionId, 'failed', 'Modify operation failed', data);
      });
 
      // Listen for history management events
      this.eventBus.on('clearHistory', () => {
        this.clearHistory();
      });
      this.eventBus.on('exportHistory', data => {
        this.exportHistory(data.options);
      });
      this.eventBus.on('filterHistory', data => {
        this.setFilter(data.filter);
      });
    }
  }
 
  /**
   * Add a new history entry
   */
  addHistoryEntry(category, description, status) {
    let data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    const entry = {
      id: this.generateHistoryId(),
      timestamp: new Date().toISOString(),
      category,
      description,
      status,
      data: this.sanitizeHistoryData(data),
      sessionId: data.sessionId || this.generateSessionId(),
      duration: null,
      startTime: new Date().toISOString()
    };
 
    // Add to beginning of history array
    this.history.unshift(entry);
 
    // Maintain history size limit
    if (this.history.length > this.maxHistorySize) {
      this.history = this.history.slice(0, this.maxHistorySize);
    }
 
    // Save to storage
    this.saveHistoryToStorage();
 
    // Log the history entry
    if (this.loggingSubsystem) {
      this.loggingSubsystem.info('History entry added', {
        category,
        description,
        status,
        sessionId: entry.sessionId
      }, 'system');
    }
 
    // Emit event for UI updates
    if (this.eventBus) {
      this.eventBus.emit('historyEntryAdded', entry);
    }
    return entry.id;
  }
 
  /**
   * Update an existing history entry
   */
  updateHistoryEntry(sessionId, status) {
    let description = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    let data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    const entry = this.history.find(h => h.sessionId === sessionId);
    if (entry) {
      entry.status = status;
      entry.timestamp = new Date().toISOString();
      if (description) {
        entry.description = description;
      }
 
      // Calculate duration if operation is complete
      if (['completed', 'failed', 'cancelled'].includes(status) && entry.startTime) {
        entry.duration = new Date() - new Date(entry.startTime);
      }
 
      // Merge additional data
      if (data && Object.keys(data).length > 0) {
        entry.data = {
          ...entry.data,
          ...this.sanitizeHistoryData(data)
        };
      }
 
      // Save to storage
      this.saveHistoryToStorage();
 
      // Log the update
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info('History entry updated', {
          sessionId,
          status,
          description,
          duration: entry.duration
        }, 'system');
      }
 
      // Emit event for UI updates
      if (this.eventBus) {
        this.eventBus.emit('historyEntryUpdated', entry);
      }
      return true;
    }
    if (this.loggingSubsystem) {
      this.loggingSubsystem.warn('History entry not found for update', {
        sessionId
      }, 'system');
    }
    return false;
  }
 
  /**
   * Get filtered history entries
   */
  async getHistory() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    try {
      const {
        limit = 50,
        offset = 0,
        category = null,
        status = null,
        search = null,
        startDate = null,
        endDate = null,
        sortBy = 'timestamp',
        sortOrder = 'desc'
      } = options;
      let filteredHistory = [...this.history];
 
      // Apply filters
      if (category) {
        filteredHistory = filteredHistory.filter(entry => entry.category === category);
      }
      if (status) {
        filteredHistory = filteredHistory.filter(entry => entry.status === status);
      }
      if (search) {
        const searchLower = search.toLowerCase();
        filteredHistory = filteredHistory.filter(entry => entry.description.toLowerCase().includes(searchLower) || JSON.stringify(entry.data).toLowerCase().includes(searchLower));
      }
      if (startDate) {
        filteredHistory = filteredHistory.filter(entry => new Date(entry.timestamp) >= new Date(startDate));
      }
      if (endDate) {
        filteredHistory = filteredHistory.filter(entry => new Date(entry.timestamp) <= new Date(endDate));
      }
 
      // Apply sorting
      filteredHistory.sort((a, b) => {
        const aValue = a[sortBy];
        const bValue = b[sortBy];
        if (sortOrder === 'asc') {
          return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
        } else {
          return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
        }
      });
 
      // Apply pagination
      const paginatedHistory = filteredHistory.slice(offset, offset + limit);
      const result = {
        history: paginatedHistory,
        total: filteredHistory.length,
        hasMore: offset + limit < filteredHistory.length,
        stats: this.getHistoryStats(filteredHistory)
      };
      if (this.loggingSubsystem) {
        this.loggingSubsystem.debug('History retrieved', {
          requested: limit,
          returned: paginatedHistory.length,
          total: result.total,
          filters: {
            category,
            status,
            search
          }
        }, 'system');
      }
      return result;
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to get history', error, 'system');
      }
      throw error;
    }
  }
 
  /**
   * Get history statistics
   */
  getHistoryStats() {
    let historyData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    const data = historyData || this.history;
    const stats = {
      total: data.length,
      categories: {},
      statuses: {},
      recentActivity: data.slice(0, 5),
      averageDuration: 0,
      totalDuration: 0
    };
    let durationCount = 0;
    let totalDuration = 0;
    data.forEach(entry => {
      // Count by category
      stats.categories[entry.category] = (stats.categories[entry.category] || 0) + 1;
 
      // Count by status
      stats.statuses[entry.status] = (stats.statuses[entry.status] || 0) + 1;
 
      // Calculate duration stats
      if (entry.duration) {
        totalDuration += entry.duration;
        durationCount++;
      }
    });
    if (durationCount > 0) {
      stats.averageDuration = totalDuration / durationCount;
      stats.totalDuration = totalDuration;
    }
    return stats;
  }
 
  /**
   * Set history filter
   */
  setFilter(filter) {
    this.currentFilter = {
      ...this.currentFilter,
      ...filter
    };
    if (this.loggingSubsystem) {
      this.loggingSubsystem.debug('History filter updated', this.currentFilter, 'system');
    }
 
    // Emit event for UI updates
    if (this.eventBus) {
      this.eventBus.emit('historyFilterChanged', this.currentFilter);
    }
  }
 
  /**
   * Clear all history
   */
  clearHistory() {
    const previousCount = this.history.length;
    this.history = [];
 
    // Clear from storage
    this.saveHistoryToStorage();
    if (this.loggingSubsystem) {
      this.loggingSubsystem.info('History cleared', {
        previousCount
      }, 'system');
    }
 
    // Emit event for UI updates
    if (this.eventBus) {
      this.eventBus.emit('historyCleared', {
        previousCount
      });
    }
  }
 
  /**
   * Export history to file
   */
  async exportHistory() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    try {
      const {
        format = 'json',
        filename = `history_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}`,
        includeData = true
      } = options;
      const historyData = await this.getHistory({
        limit: this.maxHistorySize
      });
      let content;
      let mimeType;
      let extension;
 
      // Prepare export data
      const exportData = historyData.history.map(entry => ({
        id: entry.id,
        timestamp: entry.timestamp,
        category: entry.category,
        description: entry.description,
        status: entry.status,
        duration: entry.duration,
        ...(includeData && {
          data: entry.data
        })
      }));
      switch (format.toLowerCase()) {
        case 'csv':
          content = this.convertHistoryToCSV(exportData);
          mimeType = 'text/csv';
          extension = 'csv';
          break;
        case 'txt':
          content = this.convertHistoryToText(exportData);
          mimeType = 'text/plain';
          extension = 'txt';
          break;
        case 'json':
        default:
          content = JSON.stringify({
            exportDate: new Date().toISOString(),
            stats: historyData.stats,
            history: exportData
          }, null, 2);
          mimeType = 'application/json';
          extension = 'json';
          break;
      }
 
      // Create and download file
      const blob = new Blob([content], {
        type: mimeType
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${filename}.${extension}`;
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info('History exported successfully', {
          format,
          filename: `${filename}.${extension}`,
          entryCount: exportData.length
        }, 'system');
      }
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to export history', error, 'system');
      }
      throw error;
    }
  }
 
  /**
   * Convert history to CSV format
   */
  convertHistoryToCSV(history) {
    const headers = ['ID', 'Timestamp', 'Category', 'Description', 'Status', 'Duration'];
    const csvRows = [headers.join(',')];
    history.forEach(entry => {
      const row = [entry.id, entry.timestamp, entry.category, `"${entry.description.replace(/"/g, '""')}"`, entry.status, entry.duration || ''];
      csvRows.push(row.join(','));
    });
    return csvRows.join('\n');
  }
 
  /**
   * Convert history to text format
   */
  convertHistoryToText(history) {
    return history.map(entry => {
      const duration = entry.duration ? ` (${Math.round(entry.duration / 1000)}s)` : '';
      return `[${entry.timestamp}] ${entry.category.toUpperCase()} [${entry.status.toUpperCase()}] ${entry.description}${duration}`;
    }).join('\n');
  }
 
  /**
   * Load history from local storage
   */
  async loadHistoryFromStorage() {
    try {
      const stored = localStorage.getItem('pingone-import-history');
      if (stored) {
        const parsedHistory = JSON.parse(stored);
        if (Array.isArray(parsedHistory)) {
          this.history = parsedHistory;
          if (this.loggingSubsystem) {
            this.loggingSubsystem.info('History loaded from storage', {
              entryCount: this.history.length
            }, 'system');
          }
        }
      }
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.warn('Failed to load history from storage', error, 'system');
      }
    }
  }
 
  /**
   * Save history to local storage
   */
  saveHistoryToStorage() {
    try {
      localStorage.setItem('pingone-import-history', JSON.stringify(this.history));
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.warn('Failed to save history to storage', error, 'system');
      }
    }
  }
 
  /**
   * Sanitize history data to prevent circular references and sensitive data
   */
  sanitizeHistoryData(data) {
    if (!data || typeof data !== 'object') {
      return data;
    }
    try {
      return JSON.parse(JSON.stringify(data, (key, value) => {
        // Remove sensitive fields
        const sensitiveFields = ['password', 'token', 'secret', 'key', 'apiKey', 'clientSecret'];
        if (sensitiveFields.some(field => key.toLowerCase().includes(field))) {
          return '[REDACTED]';
        }
 
        // Handle circular references and complex objects
        if (typeof value === 'object' && value !== null) {
          if (value.constructor && value.constructor.name === 'HTMLElement') {
            return '[HTMLElement]';
          }
          if (value instanceof Error) {
            return {
              name: value.name,
              message: value.message
            };
          }
        }
        return value;
      }));
    } catch (error) {
      return {
        error: 'Failed to sanitize history data',
        original: String(data)
      };
    }
  }
 
  /**
   * Generate unique history ID
   */
  generateHistoryId() {
    return `hist_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
 
  /**
   * Generate session ID for operation tracking
   */
  generateSessionId() {
    return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
 
  /**
   * Get a specific history entry by ID
   */
  getHistoryEntry(id) {
    return this.history.find(entry => entry.id === id);
  }
 
  /**
   * Delete a specific history entry
   */
  deleteHistoryEntry(id) {
    const index = this.history.findIndex(entry => entry.id === id);
    if (index !== -1) {
      const deleted = this.history.splice(index, 1)[0];
      this.saveHistoryToStorage();
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info('History entry deleted', {
          id,
          description: deleted.description
        }, 'system');
      }
 
      // Emit event for UI updates
      if (this.eventBus) {
        this.eventBus.emit('historyEntryDeleted', {
          id,
          entry: deleted
        });
      }
      return true;
    }
    return false;
  }
}
 
// Export for use in other modules
exports.HistorySubsystem = HistorySubsystem;
var _default = exports.default = HistorySubsystem;
 
},{}],53:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.localAPIClient = exports.LocalAPIClient = void 0;
/**
 * Local API Client
 * Handles all API calls to the local server (localhost:4000)
 */
 
class LocalAPIClient {
  /**
   * Create a new LocalAPIClient instance
   * @param {Object} logger - Logger instance
   * @param {string} [baseUrl=''] - Base URL for the API (defaults to relative path)
   */
  constructor(logger) {
    let baseUrl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    this.logger = logger || console;
    this.baseUrl = baseUrl;
    this.serverHealth = {
      lastCheck: 0,
      isHealthy: true,
      consecutiveFailures: 0,
      maxConsecutiveFailures: 3
    };
    this.healthCheckInterval = 30000; // 30 seconds
  }
 
  /**
   * Check server health before making requests
   * @private
   */
  async _checkServerHealth() {
    const now = Date.now();
 
    // Only check health if enough time has passed since last check
    if (now - this.serverHealth.lastCheck < this.healthCheckInterval) {
      return this.serverHealth.isHealthy;
    }
    try {
      const response = await fetch(`${this.baseUrl}/api/health`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json'
        },
        signal: AbortSignal.timeout(5000) // 5 second timeout
      });
      if (response.ok) {
        this.serverHealth.isHealthy = true;
        this.serverHealth.consecutiveFailures = 0;
        this.logger.debug('✅ Server health check passed');
      } else {
        this.serverHealth.isHealthy = false;
        this.serverHealth.consecutiveFailures++;
        this.logger.warn('⚠️ Server health check failed', {
          status: response.status
        });
      }
    } catch (error) {
      this.serverHealth.isHealthy = false;
      this.serverHealth.consecutiveFailures++;
      this.logger.warn('⚠️ Server health check error', {
        error: error.message
      });
    }
    this.serverHealth.lastCheck = now;
    return this.serverHealth.isHealthy;
  }
 
  /**
   * Calculate exponential backoff delay
   * @private
   */
  _calculateBackoffDelay(attempt, baseDelay, maxDelay) {
    const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
    const jitter = Math.random() * 0.1 * exponentialDelay; // Add 10% jitter
    return Math.min(exponentialDelay + jitter, maxDelay);
  }
 
  /**
   * Determine if a request should be retried based on error type
   * @private
   */
  _shouldRetry(error, attempt, maxRetries) {
    // Don't retry if we've reached max attempts
    if (attempt >= maxRetries) {
      return false;
    }
 
    // Retry on network errors (no status code)
    if (!error.status) {
      return true;
    }
 
    // Retry on server errors (5xx)
    if (error.status >= 500) {
      return true;
    }
 
    // Retry on rate limits (429)
    if (error.status === 429) {
      return true;
    }
 
    // Retry on timeout errors (408)
    if (error.status === 408) {
      return true;
    }
 
    // Don't retry on client errors (4xx except 429, 408)
    return false;
  }
 
  /**
   * Make an API request to the local server with enhanced retry logic
   * @param {string} method - HTTP method (GET, POST, PUT, DELETE, etc.)
   * @param {string} endpoint - API endpoint (without base URL)
   * @param {Object} [data] - Request body (for POST/PUT/PATCH)
   * @param {Object} [options] - Additional options
   * @returns {Promise<Object>} Response data
   */
  async request(method, endpoint) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    const url = `${this.baseUrl}${endpoint}`;
    const startTime = Date.now();
 
    // Enhanced options with retry logic
    const requestOptions = {
      ...options,
      retries: options.retries || 3,
      retryDelay: options.retryDelay || 1000,
      // 1 second base delay
      maxRetryDelay: options.maxRetryDelay || 30000,
      // 30 seconds max delay
      healthCheck: options.healthCheck !== false,
      // Enable health check by default
      timeout: options.timeout || 10000 // 10 second timeout
    };
 
    // Check server health before making request (if enabled)
    if (requestOptions.healthCheck && endpoint !== '/api/health') {
      const isHealthy = await this._checkServerHealth();
      if (!isHealthy && this.serverHealth.consecutiveFailures >= this.serverHealth.maxConsecutiveFailures) {
        throw new Error('Server is unhealthy and unavailable for requests');
      }
    }
 
    // Prepare headers
    const headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };
 
    // Add authorization if available
    if (this.accessToken) {
      headers.Authorization = `Bearer ${this.accessToken}`;
    }
 
    // Prepare request body
    let body = null;
    if (data && method !== 'GET') {
      body = JSON.stringify(data);
    }
 
    // Log the request with minimal details to avoid rate limiting
    const requestLog = {
      type: 'api_request',
      method,
      url,
      timestamp: new Date().toISOString(),
      source: 'local-api-client'
    };
    this.logger.debug('🔄 Local API Request:', requestLog);
 
    // Retry logic with exponential backoff
    let lastError = null;
    for (let attempt = 1; attempt <= requestOptions.retries; attempt++) {
      try {
        // Create abort controller for timeout
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), requestOptions.timeout);
        const response = await fetch(url, {
          method,
          headers,
          body,
          signal: controller.signal
        });
        clearTimeout(timeoutId);
        const responseData = await this._handleResponse(response);
 
        // Log successful response with minimal details
        const responseLog = {
          type: 'api_response',
          status: response.status,
          method,
          duration: Date.now() - startTime,
          attempt: attempt,
          source: 'local-api-client'
        };
        this.logger.debug('✅ Local API Response:', responseLog);
 
        // Update server health on success
        if (requestOptions.healthCheck) {
          this.serverHealth.isHealthy = true;
          this.serverHealth.consecutiveFailures = 0;
        }
        return responseData;
      } catch (error) {
        lastError = error;
 
        // Handle timeout errors
        if (error.name === 'AbortError') {
          error.message = 'Request timeout';
          error.status = 408;
        }
        this.logger.error(`Local API Error (attempt ${attempt}/${requestOptions.retries}):`, error);
 
        // Get the friendly error message if available
        const friendlyMessage = error.friendlyMessage || error.message;
        const isRateLimit = error.status === 429;
 
        // Check if we should retry this error
        if (!this._shouldRetry(error, attempt, requestOptions.retries)) {
          throw error;
        }
 
        // Calculate backoff delay
        const baseDelay = isRateLimit ? requestOptions.retryDelay * 2 : requestOptions.retryDelay;
        const delay = this._calculateBackoffDelay(attempt, baseDelay, requestOptions.maxRetryDelay);
 
        // Show appropriate UI messages based on error type
        if (window.app && window.app.uiManager) {
          if (isRateLimit) {
            if (attempt < requestOptions.retries) {
              // Use enhanced rate limit warning with retry information
              window.app.uiManager.showRateLimitWarning(friendlyMessage, {
                isRetrying: true,
                retryAttempt: attempt,
                maxRetries: requestOptions.retries,
                retryDelay: delay
              });
            } else {
              window.app.uiManager.showError(friendlyMessage);
            }
          } else if (attempt === requestOptions.retries) {
            // For other errors, show friendly message on final attempt
            window.app.uiManager.showError(friendlyMessage);
          }
        }
 
        // Update server health on failure
        if (requestOptions.healthCheck) {
          this.serverHealth.isHealthy = false;
          this.serverHealth.consecutiveFailures++;
        }
 
        // If this is the last attempt, throw with friendly message
        if (attempt === requestOptions.retries) {
          throw error;
        }
 
        // Log retry attempt
        this.logger.info(`Retrying request in ${delay}ms... (attempt ${attempt + 1}/${requestOptions.retries})`);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
 
    // If all retries fail, throw the last error
    throw lastError;
  }
 
  /**
   * Handle API response
   * @private
   */
  async _handleResponse(response) {
    const contentType = response.headers.get('content-type');
    let data;
    if (contentType && contentType.includes('application/json')) {
      data = await response.json();
    } else {
      data = await response.text();
    }
    if (!response.ok) {
      let errorMessage;
 
      // Provide user-friendly error messages based on status code
      switch (response.status) {
        case 400:
          errorMessage = this._getBadRequestMessage(data, response.url);
          break;
        case 401:
          errorMessage = this._getUnauthorizedMessage();
          break;
        case 403:
          errorMessage = this._getForbiddenMessage(data, response.url);
          break;
        case 404:
          errorMessage = this._getNotFoundMessage(data, response.url);
          break;
        case 429:
          errorMessage = this._getRateLimitMessage();
          break;
        case 500:
        case 501:
        case 502:
        case 503:
        case 504:
          errorMessage = this._getServerErrorMessage(response.status);
          break;
        default:
          errorMessage = data.message || `Request failed with status ${response.status}`;
      }
      const error = new Error(errorMessage);
      error.status = response.status;
      error.details = data;
      error.friendlyMessage = errorMessage;
      throw error;
    }
    return data;
  }
 
  /**
   * Get user-friendly error message for 400 Bad Request errors
   * @private
   */
  _getBadRequestMessage(data, url) {
    // Check if it's an import endpoint error
    if (url.includes('/import')) {
      if (data && data.error) {
        // Return the specific error message from the server
        return data.error;
      }
      if (data && data.message) {
        return data.message;
      }
      return '🔍 Import failed. Please check your CSV file and settings.';
    }
 
    // Check if it's a user modification endpoint
    if (url.includes('/users/') && url.includes('PUT')) {
      return '🔍 User data validation failed. Please check the user information and try again.';
    }
 
    // Check if it's a user creation endpoint
    if (url.includes('/users') && url.includes('POST')) {
      return '🔍 User creation failed due to invalid data. Please check required fields and try again.';
    }
 
    // Check if it's a population-related error
    if (url.includes('/populations')) {
      return '🔍 Population data is invalid. Please check your population settings.';
    }
 
    // Generic 400 error
    return '🔍 Request data is invalid. Please check your input and try again.';
  }
 
  /**
   * Get user-friendly error message for 401 Unauthorized errors
   * @private
   */
  _getUnauthorizedMessage() {
    return '🔑 Authentication failed. Please check your PingOne API credentials in the Settings page.';
  }
 
  /**
   * Get user-friendly error message for 403 Forbidden errors
   * @private
   */
  _getForbiddenMessage(data, url) {
    // Check if it's a user modification endpoint
    if (url.includes('/users/') && url.includes('PUT')) {
      return '🚫 Permission denied. Your PingOne application may not have permission to modify users.';
    }
 
    // Check if it's a user creation endpoint
    if (url.includes('/users') && url.includes('POST')) {
      return '🚫 Permission denied. Your PingOne application may not have permission to create users.';
    }
 
    // Check if it's a user deletion endpoint
    if (url.includes('/users/') && url.includes('DELETE')) {
      return '🚫 Permission denied. Your PingOne application may not have permission to delete users.';
    }
 
    // Generic 403 error
    return '🚫 Access denied. Your PingOne application may not have the required permissions for this operation.';
  }
 
  /**
   * Get user-friendly error message for 404 Not Found errors
   * @private
   */
  _getNotFoundMessage(data, url) {
    // Check if it's a user-related endpoint
    if (url.includes('/users/')) {
      return '🔍 User not found. The user may have been deleted or the ID is incorrect.';
    }
 
    // Check if it's a population-related endpoint
    if (url.includes('/populations')) {
      return '🔍 Population not found. Please check your population settings.';
    }
 
    // Check if it's an environment-related endpoint
    if (url.includes('/environments/')) {
      return '🔍 PingOne environment not found. Please check your environment ID.';
    }
 
    // Generic 404 error
    return '🔍 Resource not found. Please check the ID or settings and try again.';
  }
 
  /**
   * Get user-friendly error message for 429 Too Many Requests errors
   * @private
   */
  _getRateLimitMessage() {
    return '⏰ You are sending requests too quickly. Please wait a moment and try again.';
  }
 
  /**
   * Get user-friendly error message for 500+ server errors
   * @private
   */
  _getServerErrorMessage(status) {
    if (status >= 500) {
      return '🔧 Server error. Please check your PingOne API credentials in the Settings page.';
    }
    return '🔧 An unexpected error occurred. Please try again.';
  }
 
  // Convenience methods for common HTTP methods
  get(endpoint) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return this.request('GET', endpoint, null, options);
  }
  post(endpoint, data) {
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    return this.request('POST', endpoint, data, options);
  }
 
  /**
   * Send a POST request with FormData (for file uploads)
   * @param {string} endpoint - API endpoint
   * @param {FormData} formData - FormData object
   * @param {Object} options - Additional options
   * @returns {Promise<Object>} Response data
   */
  async postFormData(endpoint, formData) {
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const url = `${this.baseUrl}${endpoint}`;
    const startTime = Date.now();
 
    // Enhanced options with retry logic
    const requestOptions = {
      ...options,
      retries: options.retries || 3,
      retryDelay: options.retryDelay || 1000 // 1 second base delay
    };
 
    // Prepare headers for FormData (don't set Content-Type, let browser set it with boundary)
    const headers = {
      'Accept': 'application/json'
    };
 
    // Add authorization if available
    if (this.accessToken) {
      headers.Authorization = `Bearer ${this.accessToken}`;
    }
 
    // Log the request with minimal details to avoid rate limiting
    const requestLog = {
      type: 'api_request',
      method: 'POST',
      url,
      timestamp: new Date().toISOString(),
      source: 'local-api-client',
      contentType: 'multipart/form-data'
    };
    this.logger.debug('🔄 Local API FormData Request:', requestLog);
 
    // Retry logic
    let lastError = null;
    for (let attempt = 1; attempt <= requestOptions.retries; attempt++) {
      try {
        const response = await fetch(url, {
          method: 'POST',
          headers,
          body: formData
        });
        const responseData = await this._handleResponse(response);
 
        // Log successful response with minimal details
        const responseLog = {
          type: 'api_response',
          status: response.status,
          method: 'POST',
          duration: Date.now() - startTime,
          attempt: attempt,
          source: 'local-api-client'
        };
        this.logger.debug('✅ Local API FormData Response:', responseLog);
        return responseData;
      } catch (error) {
        lastError = error;
        this.logger.error(`Local API FormData Error (attempt ${attempt}/${requestOptions.retries}):`, error);
 
        // Get the friendly error message if available
        const friendlyMessage = error.friendlyMessage || error.message;
        const isRateLimit = error.status === 429;
 
        // Calculate baseDelay and delay here, before using them
        const baseDelay = isRateLimit ? requestOptions.retryDelay * 2 : requestOptions.retryDelay;
        const delay = baseDelay * Math.pow(2, attempt - 1);
 
        // Show appropriate UI messages based on error type
        if (window.app && window.app.uiManager) {
          if (isRateLimit) {
            if (attempt < requestOptions.retries) {
              // Use enhanced rate limit warning with retry information
              window.app.uiManager.showRateLimitWarning(friendlyMessage, {
                isRetrying: true,
                retryAttempt: attempt,
                maxRetries: requestOptions.retries,
                retryDelay: delay
              });
            } else {
              window.app.uiManager.showError(friendlyMessage);
            }
          } else if (attempt === requestOptions.retries) {
            // For other errors, show friendly message on final attempt
            window.app.uiManager.showError(friendlyMessage);
          }
        }
 
        // If this is the last attempt, throw with friendly message
        if (attempt === requestOptions.retries) {
          throw error;
        }
 
        // Only retry for rate limits (429) and server errors (5xx)
        const shouldRetry = isRateLimit || error.status >= 500 || !error.status;
        if (!shouldRetry) {
          // Don't retry for client errors (4xx except 429), throw immediately
          throw error;
        }
 
        // Use the delay calculated above
        this.logger.info(`Retrying FormData request in ${delay}ms... (attempt ${attempt + 1}/${requestOptions.retries})`);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
 
    // If all retries fail, throw the last error
    throw lastError;
  }
  put(endpoint, data) {
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    return this.request('PUT', endpoint, data, options);
  }
  delete(endpoint) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return this.request('DELETE', endpoint, null, options);
  }
 
  // Token Management Methods
 
  /**
   * Retrieve PingOne worker token
   * @returns {Promise<Object>} Token data with expiration info
   */
  async getWorkerToken() {
    this.logger.debug('🔐 Retrieving PingOne worker token...');
    try {
      const response = await this.post('/api/auth/worker-token', {}, {
        timeout: 15000,
        // 15 second timeout for token retrieval
        retries: 2 // Fewer retries for token operations
      });
      this.logger.debug('✅ Worker token retrieved successfully');
      return response;
    } catch (error) {
      this.logger.error('❌ Failed to retrieve worker token:', error);
      throw new Error(`Token retrieval failed: ${error.message}`);
    }
  }
 
  /**
   * Refresh existing PingOne worker token
   * @param {string} currentToken - Current token for authorization
   * @returns {Promise<Object>} Refreshed token data
   */
  async refreshWorkerToken(currentToken) {
    this.logger.debug('🔄 Refreshing PingOne worker token...');
    if (!currentToken) {
      throw new Error('Current token is required for refresh');
    }
    try {
      const response = await this.post('/api/auth/refresh-token', {}, {
        headers: {
          'Authorization': `Bearer ${currentToken}`
        },
        timeout: 10000,
        // 10 second timeout for refresh
        retries: 1 // Single retry for refresh operations
      });
      this.logger.debug('✅ Worker token refreshed successfully');
      return response;
    } catch (error) {
      this.logger.error('❌ Failed to refresh worker token:', error);
      throw new Error(`Token refresh failed: ${error.message}`);
    }
  }
 
  /**
   * Get current token status without retrieving the actual token
   * @returns {Promise<Object>} Token status information
   */
  async getTokenStatus() {
    this.logger.debug('🔍 Checking worker token status...');
    try {
      const response = await this.get('/api/auth/token-status', {
        timeout: 5000,
        // 5 second timeout for status check
        retries: 1 // Single retry for status check
      });
      this.logger.debug('✅ Token status retrieved successfully');
      return response;
    } catch (error) {
      this.logger.debug('ℹ️ Could not retrieve token status:', error.message);
      // Don't throw for status checks - return null status
      return {
        success: false,
        hasToken: false,
        error: error.message
      };
    }
  }
 
  /**
   * Clear/invalidate current worker token
   * @returns {Promise<Object>} Clear operation result
   */
  async clearWorkerToken() {
    this.logger.debug('🗑️ Clearing worker token...');
    try {
      const response = await this.delete('/api/auth/worker-token', {
        timeout: 5000,
        // 5 second timeout for clear operation
        retries: 1 // Single retry for clear operation
      });
      this.logger.debug('✅ Worker token cleared successfully');
      return response;
    } catch (error) {
      this.logger.error('❌ Failed to clear worker token:', error);
      throw new Error(`Token clear failed: ${error.message}`);
    }
  }
 
  /**
   * Validate worker token and get detailed information
   */
  async validateToken() {
    let token = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    try {
      const payload = token ? {
        token: token
      } : {};
      const response = await this.post('/api/auth/validate-credentials', payload, {
        timeout: 5000,
        // 5 second timeout for validation
        retries: 1 // Single retry for validation
      });
      return {
        success: true,
        valid: response.valid || false,
        details: response.details || {},
        message: response.message || 'Token validation completed'
      };
    } catch (error) {
      return {
        success: false,
        valid: false,
        error: error.message,
        message: 'Token validation failed'
      };
    }
  }
 
  /**
   * Test API connection
   * @returns {Promise<Object>} Connection test result
   */
  async testConnection() {
    try {
      // CRITICAL: This MUST be a GET request to /api/pingone/test-connection
      // Server endpoint: routes/pingone-proxy-fixed.js - router.get('/test-connection')
      // DO NOT change to POST without updating server-side endpoint
      // Last fixed: 2025-07-21 - Fixed HTTP method mismatch causing 400 Bad Request errors
      const response = await this.get('/api/pingone/test-connection', {
        timeout: 10000,
        // 10 second timeout for connection test
        retries: 1 // Single retry for connection test
      });
      return {
        success: true,
        connected: true,
        details: response.details || {},
        message: response.message || 'Connection successful'
      };
    } catch (error) {
      return {
        success: false,
        connected: false,
        error: error.message,
        message: 'Connection test failed'
      };
    }
  }
}
 
// Export a singleton instance
exports.LocalAPIClient = LocalAPIClient;
const localAPIClient = exports.localAPIClient = new LocalAPIClient(console);
 
},{}],54:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Logger = void 0;
var _winstonLogger = require("./winston-logger.js");
var _messageFormatter = _interopRequireDefault(require("./message-formatter.js"));
var _uiManager = require("./ui-manager.js");
function _interopRequireWildcard(e, t) {
  if ("function" == typeof WeakMap) var r = new WeakMap(),
    n = new WeakMap();
  return (_interopRequireWildcard = function (e, t) {
    if (!t && e && e.__esModule) return e;
    var o,
      i,
      f = {
        __proto__: null,
        default: e
      };
    if (null === e || "object" != typeof e && "function" != typeof e) return f;
    if (o = t ? n : r) {
      if (o.has(e)) return o.get(e);
      o.set(e, f);
    }
    for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]);
    return f;
  })(e, t);
} /**
  * @fileoverview Winston-compatible logger for frontend environment
  * 
  * This module provides a Winston-like logging interface for the frontend
  * that maintains consistency with server-side Winston logging while
  * working within browser constraints.
  * 
  * Features:
  * - Winston-compatible API (info, warn, error, debug)
  * - Structured logging with metadata
  * - Timestamp formatting
  * - Log level filtering
  * - Console and server transport support
  * - Error stack trace handling
  * - Environment-aware configuration
  */
const ui = window.app && window.app.uiManager;
 
/**
 * Winston-compatible logger for browser environment
 */
class Logger {
  constructor() {
    let logElement = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    // Handle different types of logElement parameters
    if (typeof logElement === 'string') {
      // If string provided, try to find DOM element or set to null for UI-less logging
      try {
        const element = document.getElementById(logElement) || document.querySelector(logElement);
        this.logElement = element;
        if (!element) {
          console.debug(`[LOGGER] DOM element not found for '${logElement}', using UI-less logging`);
        }
      } catch (error) {
        console.debug(`[LOGGER] Error finding DOM element for '${logElement}':`, error.message);
        this.logElement = null;
      }
    } else if (logElement && logElement.nodeType === Node.ELEMENT_NODE) {
      // Valid DOM element
      this.logElement = logElement;
    } else if (logElement && typeof logElement === 'object' && logElement.length !== undefined) {
      // Handle NodeList/HTMLCollection - take first element
      this.logElement = logElement.length > 0 ? logElement[0] : null;
      if (logElement.length > 1) {
        console.debug(`[LOGGER] Multiple elements found, using first element`);
      }
    } else {
      // Null, undefined, or invalid - use UI-less logging
      this.logElement = null;
    }
    this.logs = [];
    this.validCount = 0;
    this.errorCount = 0;
    this.initialized = false;
    this.serverLoggingEnabled = true;
    this.isLoadingLogs = false;
    this.offlineLogs = [];
 
    // Initialize Winston-compatible logger
    this.winstonLogger = (0, _winstonLogger.createWinstonLogger)({
      service: 'pingone-import-frontend',
      environment: process.env.NODE_ENV || 'development',
      enableServerLogging: true,
      enableConsoleLogging: true
    });
    this.initialize();
  }
 
  /**
   * Initialize the logger
   */
  initialize() {
    try {
      this.winstonLogger.info('Logger initialized successfully');
      this.initialized = true;
    } catch (error) {
      console.error('Failed to initialize logger:', error);
    }
  }
 
  /**
   * Temporarily disable server logging to prevent feedback loops
   */
  disableServerLogging() {
    this.serverLoggingEnabled = false;
    this.winstonLogger.setServerLogging(false);
    this.winstonLogger.debug('Server logging disabled');
  }
 
  /**
   * Re-enable server logging
   */
  enableServerLogging() {
    this.serverLoggingEnabled = true;
    this.winstonLogger.setServerLogging(true);
    this.winstonLogger.debug('Server logging enabled');
  }
 
  /**
   * Set flag to indicate we're loading logs (prevents server logging)
   */
  setLoadingLogs(isLoading) {
    this.isLoadingLogs = isLoading;
    this.winstonLogger.debug(`Loading logs flag set to: ${isLoading}`);
  }
 
  /**
   * Create a safe file logger that handles initialization and errors
   * @private
   */
  _createSafeFileLogger() {
    const logger = {
      _initialized: false,
      _logger: null,
      _queue: [],
      _initializing: false,
      async init() {
        if (this._initialized || this._initializing) return;
        this._initializing = true;
        try {
          // Initialize actual FileLogger for client.log
          const {
            FileLogger
          } = await Promise.resolve().then(() => _interopRequireWildcard(require('./file-logger.js')));
          this._logger = new FileLogger('client.log');
          this._initialized = true;
          this._processQueue();
        } catch (error) {
          console.warn('Failed to initialize file logger, falling back to console:', error.message);
          // Fallback to console logging
          this._logger = {
            log: (level, message, data) => {
              console[level] || console.log(`[${level.toUpperCase()}] ${message}`, data);
            }
          };
          this._initialized = true;
          this._processQueue();
        } finally {
          this._initializing = false;
        }
      },
      _processQueue() {
        while (this._queue.length > 0) {
          const {
            level,
            message,
            data
          } = this._queue.shift();
          if (this._logger && typeof this._logger.log === 'function') {
            this._logger.log(level, message, data);
          }
        }
      },
      log(level, message, data) {
        if (this._initialized && this._logger) {
          this._logger.log(level, message, data);
        } else {
          this._queue.push({
            level,
            message,
            data
          });
          if (!this._initializing) {
            this.init();
          }
        }
      }
    };
    return logger;
  }
 
  /**
   * Parse log arguments into structured format
   * @private
   */
  _parseLogArgs(args) {
    let message = 'Log message';
    let data = null;
    let context = null;
    if (args.length > 0) {
      if (typeof args[0] === 'string') {
        message = args[0];
        if (args.length > 1 && typeof args[1] === 'object') {
          data = args[1];
          if (args.length > 2 && typeof args[2] === 'object') {
            context = args[2];
          }
        }
      } else if (typeof args[0] === 'object') {
        data = args[0];
        message = 'Log data';
        if (args.length > 1 && typeof args[1] === 'object') {
          context = args[1];
        }
      }
    }
    return [message, data, context];
  }
 
  /**
   * Main logging method with Winston integration
   */
  log(level, message) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    try {
      // Parse arguments if needed
      if (typeof level === 'string' && typeof message === 'string') {
        // Direct call: log(level, message, data)
        this._logToWinston(level, message, data);
      } else {
        // Legacy call: log(message, level)
        const [parsedMessage, parsedData, context] = this._parseLogArgs(arguments);
        this._logToWinston(level || 'info', parsedMessage, {
          ...parsedData,
          ...context
        });
      }
 
      // Update UI if log element exists
      this._updateLogUI({
        level,
        message,
        data,
        timestamp: new Date()
      });
    } catch (error) {
      console.error('Error in logger.log:', error);
    }
  }
 
  /**
   * Log to Winston with proper formatting
   * @private
   */
  _logToWinston(level, message) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const logData = {
      ...data,
      component: 'frontend-logger',
      timestamp: new Date().toISOString()
    };
    this.winstonLogger.log(level, message, logData);
  }
 
  /**
   * Log info level message
   */
  info(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('info', message, data);
  }
 
  /**
   * Log warn level message
   */
  warn(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('warn', message, data);
  }
 
  /**
   * Log error level message
   */
  error(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('error', message, data);
    if (ui) ui.showStatusBar(message, 'error', {
      autoDismiss: false
    });
    this.errorCount++;
    this.updateSummary();
  }
 
  /**
   * Log debug level message
   */
  debug(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('debug', message, data);
  }
 
  /**
   * Log success level message
   */
  success(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('info', message, {
      ...data,
      type: 'success'
    });
    this.validCount++;
    this.updateSummary();
  }
 
  /**
   * Log error with stack trace
   */
  errorWithStack(message, error) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    this.winstonLogger.errorWithStack(message, error, data);
    this.errorCount++;
    this.updateSummary();
  }
 
  /**
   * Update log UI with new entry
   * @private
   */
  _updateLogUI(logEntry) {
    if (!this.logElement) return;
    try {
      const logElement = document.createElement('div');
      logElement.className = `log-entry ${logEntry.level}`;
 
      // Create timestamp
      const timestamp = document.createElement('span');
      timestamp.className = 'log-timestamp';
      timestamp.textContent = new Date(logEntry.timestamp).toLocaleTimeString();
      logElement.appendChild(timestamp);
 
      // Create level badge
      const levelBadge = document.createElement('span');
      levelBadge.className = 'log-level';
      levelBadge.textContent = logEntry.level.toUpperCase();
      logElement.appendChild(levelBadge);
 
      // Create message with formatting
      const message = document.createElement('span');
      message.className = 'log-message';
 
      // Format the message for better readability
      let formattedMessage = logEntry.message;
      if (logEntry.data && logEntry.data.type) {
        // Format based on message type
        switch (logEntry.data.type) {
          case 'progress':
            formattedMessage = _messageFormatter.default.formatProgressMessage(logEntry.data.operation || 'import', logEntry.data.current || 0, logEntry.data.total || 0, logEntry.message, logEntry.data.counts || {});
            break;
          case 'error':
            formattedMessage = _messageFormatter.default.formatErrorMessage(logEntry.data.operation || 'import', logEntry.message, logEntry.data);
            break;
          case 'completion':
            formattedMessage = _messageFormatter.default.formatCompletionMessage(logEntry.data.operation || 'import', logEntry.data);
            break;
          default:
            // Use original message for other types
            formattedMessage = logEntry.message;
        }
      }
      message.textContent = formattedMessage;
      logElement.appendChild(message);
 
      // Add details if present
      if (logEntry.data && Object.keys(logEntry.data).length > 0) {
        const detailsElement = document.createElement('div');
        detailsElement.className = 'log-details';
        const detailsTitle = document.createElement('h4');
        detailsTitle.textContent = 'Details';
        detailsElement.appendChild(detailsTitle);
        const detailsContent = document.createElement('pre');
        detailsContent.className = 'log-detail-json';
        detailsContent.textContent = JSON.stringify(logEntry.data, null, 2);
        detailsElement.appendChild(detailsContent);
        logElement.appendChild(detailsElement);
      }
 
      // Insert at top (newest first)
      if (this.logElement.firstChild) {
        this.logElement.insertBefore(logElement, this.logElement.firstChild);
      } else {
        this.logElement.appendChild(logElement);
      }
 
      // Auto-scroll to top
      this.logElement.scrollTop = 0;
 
      // Limit UI logs
      const maxUILogs = 100;
      while (this.logElement.children.length > maxUILogs) {
        this.logElement.removeChild(this.logElement.lastChild);
      }
    } catch (error) {
      console.error('Error updating log UI:', error);
    }
  }
 
  /**
   * Send log to server
   * @private
   */
  async _sendToServer(logEntry) {
    if (!this.serverLoggingEnabled || this.isLoadingLogs) {
      return;
    }
    try {
      await fetch('/api/logs/ui', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          level: logEntry.level,
          message: logEntry.message,
          data: logEntry.data
        })
      });
    } catch (error) {
      this.winstonLogger.warn('Failed to send log to server', {
        error: error.message
      });
      this.offlineLogs.push(logEntry);
    }
  }
 
  /**
   * Render all logs to UI
   */
  renderLogs() {
    if (!this.logElement) return;
    this.logElement.innerHTML = '';
    this.logs.forEach(log => this._updateLogUI(log));
    this.logElement.scrollTop = this.logElement.scrollHeight;
  }
 
  /**
   * Clear all logs
   */
  clearLogs() {
    this.logs = [];
    if (this.logElement) {
      this.logElement.innerHTML = '';
    }
    this.winstonLogger.info('Logs cleared');
  }
 
  /**
   * Get all logs
   */
  getLogs() {
    return [...this.logs];
  }
 
  /**
   * Update summary display
   */
  updateSummary() {
    // Implementation depends on UI structure
    this.winstonLogger.debug('Summary updated', {
      validCount: this.validCount,
      errorCount: this.errorCount
    });
  }
 
  /**
   * Clear summary
   */
  clearSummary() {
    this.validCount = 0;
    this.errorCount = 0;
    this.winstonLogger.debug('Summary cleared');
  }
 
  /**
   * Start a performance timer
   */
  startTimer(label) {
    if (!this.timers) {
      this.timers = new Map();
    }
    this.timers.set(label, Date.now());
    this.debug(`Timer started: ${label}`);
  }
 
  /**
   * End a performance timer and log the duration
   */
  endTimer(label) {
    if (!this.timers || !this.timers.has(label)) {
      this.warn(`Timer '${label}' not found`);
      return 0;
    }
    const startTime = this.timers.get(label);
    const duration = Date.now() - startTime;
    this.timers.delete(label);
    this.info(`Timer completed: ${label}`, {
      duration: `${duration}ms`
    });
    return duration;
  }
 
  /**
   * Create a child logger with additional context
   * This is required for hierarchical logging in subsystems
   */
  child() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    console.log('🔥 [LOGGER DEBUG] Creating child logger with options:', options);
 
    // Create a new logger instance that inherits from this one
    const childLogger = Object.create(this);
 
    // Add context from options
    childLogger.context = {
      ...this.context,
      ...options
    };
 
    // Override logging methods to include context
    const originalMethods = ['info', 'warn', 'error', 'debug'];
    originalMethods.forEach(method => {
      const originalMethod = this[method].bind(this);
      childLogger[method] = function (message) {
        let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
        const contextualData = {
          ...childLogger.context,
          ...data
        };
        return originalMethod(message, contextualData);
      };
    });
    console.log('🔥 [LOGGER DEBUG] Child logger created successfully');
    return childLogger;
  }
}
 
// Export the Logger class
exports.Logger = Logger;
 
}).call(this)}).call(this,require('_process'))
},{"./file-logger.js":51,"./message-formatter.js":56,"./ui-manager.js":68,"./winston-logger.js":70,"@babel/runtime/helpers/interopRequireDefault":2,"_process":29}],55:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.LoggingSubsystem = void 0;
var _winstonLogger = require("./winston-logger.js");
/**
 * Logging Subsystem
 * Centralized logging system that replaces legacy window.logManager
 * Provides structured logging with levels, categories, and event integration
 */
 
class LoggingSubsystem {
  constructor(eventBus, settingsSubsystem) {
    this.eventBus = eventBus;
    this.settingsSubsystem = settingsSubsystem;
 
    // Initialize Winston logger
    this.logger = (0, _winstonLogger.createWinstonLogger)({
      service: 'logging-subsystem',
      environment: process.env.NODE_ENV || 'development'
    });
 
    // Log storage for UI display
    this.logHistory = [];
    this.maxHistorySize = 1000;
 
    // Log levels
    this.levels = {
      ERROR: 0,
      WARN: 1,
      INFO: 2,
      DEBUG: 3,
      TRACE: 4
    };
 
    // Current log level (configurable)
    this.currentLevel = this.levels.INFO;
 
    // Log categories for filtering
    this.categories = {
      SYSTEM: 'system',
      AUTH: 'auth',
      IMPORT: 'import',
      EXPORT: 'export',
      DELETE: 'delete',
      MODIFY: 'modify',
      UI: 'ui',
      API: 'api',
      ERROR: 'error'
    };
 
    // Initialize subsystem
    this.init();
    this.logger.info('LoggingSubsystem initialized successfully');
  }
 
  /**
   * Initialize the logging subsystem
   */
  async init() {
    try {
      // Load logging settings
      await this.loadSettings();
 
      // Set up event listeners
      this.setupEventListeners();
 
      // Replace global logManager if it exists
      this.replaceGlobalLogManager();
      this.logger.info('LoggingSubsystem initialization complete');
    } catch (error) {
      this.logger.error('Failed to initialize LoggingSubsystem', error);
      throw error;
    }
  }
 
  /**
   * Load logging settings from SettingsSubsystem
   */
  async loadSettings() {
    try {
      if (this.settingsSubsystem) {
        await this.settingsSubsystem.loadCurrentSettings();
        const settings = this.settingsSubsystem.currentSettings;
 
        // Set log level from settings
        if (settings.logLevel) {
          this.setLogLevel(settings.logLevel);
        }
 
        // Set max history size from settings
        if (settings.maxLogHistory) {
          this.maxHistorySize = settings.maxLogHistory;
        }
      }
    } catch (error) {
      this.logger.warn('Could not load logging settings, using defaults', error);
    }
  }
 
  /**
   * Set up event listeners for cross-subsystem communication
   */
  setupEventListeners() {
    if (this.eventBus) {
      // Listen for log level changes
      this.eventBus.on('loggingLevelChanged', data => {
        this.setLogLevel(data.level);
      });
 
      // Listen for log clear requests
      this.eventBus.on('clearLogs', () => {
        this.clearLogs();
      });
 
      // Listen for log export requests
      this.eventBus.on('exportLogs', data => {
        this.exportLogs(data.options);
      });
    }
  }
 
  /**
   * Replace global window.logManager with this subsystem
   */
  replaceGlobalLogManager() {
    // Create a compatibility layer for legacy code
    window.logManager = {
      log: (level, message, data) => this.log(level, message, data),
      error: (message, data) => this.error(message, data),
      warn: (message, data) => this.warn(message, data),
      info: (message, data) => this.info(message, data),
      debug: (message, data) => this.debug(message, data),
      loadLogs: () => this.loadLogs(),
      clearLogs: () => this.clearLogs(),
      exportLogs: options => this.exportLogs(options),
      // Legacy compatibility
      getLogger: name => this.getLogger(name)
    };
    this.logger.info('Global logManager replaced with LoggingSubsystem compatibility layer');
  }
 
  /**
   * Main logging method
   */
  log(level, message) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    let category = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : this.categories.SYSTEM;
    const levelValue = typeof level === 'string' ? this.levels[level.toUpperCase()] : level;
 
    // Check if log level is enabled
    if (levelValue > this.currentLevel) {
      return;
    }
    const logEntry = {
      timestamp: new Date().toISOString(),
      level: level.toLowerCase(),
      message,
      data: this.sanitizeLogData(data),
      category,
      sessionId: this.generateSessionId()
    };
 
    // Add to history
    this.addToHistory(logEntry);
 
    // Log to Winston
    this.logger[level.toLowerCase()](message, {
      data: logEntry.data,
      category,
      sessionId: logEntry.sessionId
    });
 
    // Emit log event for UI updates
    if (this.eventBus) {
      this.eventBus.emit('logEntry', logEntry);
    }
 
    // Console output for development
    if (process.env.NODE_ENV === 'development') {
      this.consoleLog(logEntry);
    }
  }
 
  /**
   * Error logging
   */
  error(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    let category = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.categories.ERROR;
    this.log('ERROR', message, data, category);
  }
 
  /**
   * Warning logging
   */
  warn(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    let category = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.categories.SYSTEM;
    this.log('WARN', message, data, category);
  }
 
  /**
   * Info logging
   */
  info(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    let category = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.categories.SYSTEM;
    this.log('INFO', message, data, category);
  }
 
  /**
   * Debug logging
   */
  debug(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    let category = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.categories.SYSTEM;
    this.log('DEBUG', message, data, category);
  }
 
  /**
   * Trace logging
   */
  trace(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    let category = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.categories.SYSTEM;
    this.log('TRACE', message, data, category);
  }
 
  /**
   * Get a logger instance for a specific component
   */
  getLogger(name) {
    return {
      error: (message, data) => this.error(`[${name}] ${message}`, data),
      warn: (message, data) => this.warn(`[${name}] ${message}`, data),
      info: (message, data) => this.info(`[${name}] ${message}`, data),
      debug: (message, data) => this.debug(`[${name}] ${message}`, data),
      trace: (message, data) => this.trace(`[${name}] ${message}`, data)
    };
  }
 
  /**
   * Set the current log level
   */
  setLogLevel(level) {
    if (typeof level === 'string') {
      this.currentLevel = this.levels[level.toUpperCase()] || this.levels.INFO;
    } else {
      this.currentLevel = level;
    }
    this.logger.info('Log level changed', {
      newLevel: this.currentLevel
    });
 
    // Emit event for UI updates
    if (this.eventBus) {
      this.eventBus.emit('logLevelChanged', {
        level: this.currentLevel
      });
    }
  }
 
  /**
   * Add log entry to history
   */
  addToHistory(logEntry) {
    this.logHistory.unshift(logEntry);
 
    // Maintain history size limit
    if (this.logHistory.length > this.maxHistorySize) {
      this.logHistory = this.logHistory.slice(0, this.maxHistorySize);
    }
  }
 
  /**
   * Load logs for UI display
   */
  async loadLogs() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    try {
      const {
        limit = 100,
        offset = 0,
        level = null,
        category = null,
        search = null,
        startDate = null,
        endDate = null
      } = options;
      let filteredLogs = [...this.logHistory];
 
      // Apply filters
      if (level) {
        filteredLogs = filteredLogs.filter(log => log.level === level.toLowerCase());
      }
      if (category) {
        filteredLogs = filteredLogs.filter(log => log.category === category);
      }
      if (search) {
        const searchLower = search.toLowerCase();
        filteredLogs = filteredLogs.filter(log => log.message.toLowerCase().includes(searchLower) || JSON.stringify(log.data).toLowerCase().includes(searchLower));
      }
      if (startDate) {
        filteredLogs = filteredLogs.filter(log => new Date(log.timestamp) >= new Date(startDate));
      }
      if (endDate) {
        filteredLogs = filteredLogs.filter(log => new Date(log.timestamp) <= new Date(endDate));
      }
 
      // Apply pagination
      const paginatedLogs = filteredLogs.slice(offset, offset + limit);
      const result = {
        logs: paginatedLogs,
        total: filteredLogs.length,
        hasMore: offset + limit < filteredLogs.length
      };
      this.logger.debug('Logs loaded', {
        requested: limit,
        returned: paginatedLogs.length,
        total: result.total
      });
      return result;
    } catch (error) {
      this.logger.error('Failed to load logs', error);
      throw error;
    }
  }
 
  /**
   * Clear all logs
   */
  clearLogs() {
    const previousCount = this.logHistory.length;
    this.logHistory = [];
    this.logger.info('Logs cleared', {
      previousCount
    });
 
    // Emit event for UI updates
    if (this.eventBus) {
      this.eventBus.emit('logsCleared', {
        previousCount
      });
    }
  }
 
  /**
   * Export logs to file
   */
  async exportLogs() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    try {
      const {
        format = 'json',
        filename = `logs_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}`
      } = options;
      const logs = await this.loadLogs({
        limit: this.maxHistorySize
      });
      let content;
      let mimeType;
      let extension;
      switch (format.toLowerCase()) {
        case 'csv':
          content = this.convertLogsToCSV(logs.logs);
          mimeType = 'text/csv';
          extension = 'csv';
          break;
        case 'txt':
          content = this.convertLogsToText(logs.logs);
          mimeType = 'text/plain';
          extension = 'txt';
          break;
        case 'json':
        default:
          content = JSON.stringify(logs.logs, null, 2);
          mimeType = 'application/json';
          extension = 'json';
          break;
      }
 
      // Create and download file
      const blob = new Blob([content], {
        type: mimeType
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${filename}.${extension}`;
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      this.logger.info('Logs exported successfully', {
        format,
        filename: `${filename}.${extension}`,
        logCount: logs.logs.length
      });
    } catch (error) {
      this.logger.error('Failed to export logs', error);
      throw error;
    }
  }
 
  /**
   * Convert logs to CSV format
   */
  convertLogsToCSV(logs) {
    const headers = ['Timestamp', 'Level', 'Category', 'Message', 'Data'];
    const csvRows = [headers.join(',')];
    logs.forEach(log => {
      const row = [log.timestamp, log.level, log.category, `"${log.message.replace(/"/g, '""')}"`, `"${JSON.stringify(log.data).replace(/"/g, '""')}"`];
      csvRows.push(row.join(','));
    });
    return csvRows.join('\n');
  }
 
  /**
   * Convert logs to text format
   */
  convertLogsToText(logs) {
    return logs.map(log => {
      const dataStr = Object.keys(log.data).length > 0 ? ` | Data: ${JSON.stringify(log.data)}` : '';
      return `[${log.timestamp}] ${log.level.toUpperCase()} [${log.category}] ${log.message}${dataStr}`;
    }).join('\n');
  }
 
  /**
   * Console logging for development
   */
  consoleLog(logEntry) {
    const {
      level,
      message,
      data,
      category,
      timestamp
    } = logEntry;
    const prefix = `[${timestamp}] [${category}]`;
    switch (level) {
      case 'error':
        console.error(prefix, message, data);
        break;
      case 'warn':
        console.warn(prefix, message, data);
        break;
      case 'debug':
        console.debug(prefix, message, data);
        break;
      case 'trace':
        console.trace(prefix, message, data);
        break;
      default:
        console.log(prefix, message, data);
    }
  }
 
  /**
   * Sanitize log data to prevent circular references and sensitive data
   */
  sanitizeLogData(data) {
    if (!data || typeof data !== 'object') {
      return data;
    }
    try {
      // Create a deep copy and remove sensitive fields
      const sanitized = JSON.parse(JSON.stringify(data, (key, value) => {
        // Remove sensitive fields
        const sensitiveFields = ['password', 'token', 'secret', 'key', 'apiKey', 'clientSecret'];
        if (sensitiveFields.some(field => key.toLowerCase().includes(field))) {
          return '[REDACTED]';
        }
 
        // Handle circular references
        if (typeof value === 'object' && value !== null) {
          if (value.constructor && value.constructor.name === 'HTMLElement') {
            return '[HTMLElement]';
          }
          if (value instanceof Error) {
            return {
              name: value.name,
              message: value.message,
              stack: value.stack
            };
          }
        }
        return value;
      }));
      return sanitized;
    } catch (error) {
      return {
        error: 'Failed to sanitize log data',
        original: String(data)
      };
    }
  }
 
  /**
   * Generate session ID for log tracking
   */
  generateSessionId() {
    return `log_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
 
  /**
   * Get logging statistics
   */
  getStats() {
    const stats = {
      totalLogs: this.logHistory.length,
      levelCounts: {},
      categoryCounts: {},
      recentActivity: this.logHistory.slice(0, 10)
    };
 
    // Count by level
    this.logHistory.forEach(log => {
      stats.levelCounts[log.level] = (stats.levelCounts[log.level] || 0) + 1;
      stats.categoryCounts[log.category] = (stats.categoryCounts[log.category] || 0) + 1;
    });
    return stats;
  }
}
 
// Export for use in other modules
exports.LoggingSubsystem = LoggingSubsystem;
var _default = exports.default = LoggingSubsystem;
 
}).call(this)}).call(this,require('_process'))
},{"./winston-logger.js":70,"_process":29}],56:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.MessageFormatter = void 0;
var _winstonLogger = require("./winston-logger.js");
/**
 * Enhanced Message Formatter Module
 * 
 * Improves readability of server messages with:
 * - Visual separators and formatting
 * - Structured message blocks
 * - Event grouping and labeling
 * - Timestamp formatting
 * - Color coding and styling
 * 
 * Features:
 * - Message block separation with asterisks
 * - Event start/end markers
 * - Structured formatting with line breaks
 * - Timestamp and label formatting
 * - Consistent styling across all message types
 */
 
/**
 * Enhanced Message Formatter Class
 * 
 * Formats server messages for improved readability in logs and progress windows
 */
class MessageFormatter {
  constructor() {
    this.logger = (0, _winstonLogger.createWinstonLogger)({
      service: 'pingone-message-formatter',
      environment: process.env.NODE_ENV || 'development'
    });
 
    // Message formatting options
    this.formattingOptions = {
      showTimestamps: true,
      showEventMarkers: true,
      showSeparators: true,
      maxMessageLength: 200,
      separatorChar: '*',
      separatorLength: 50
    };
 
    // Event type configurations
    this.eventTypes = {
      import: {
        start: 'IMPORT STARTED',
        end: 'IMPORT COMPLETED',
        error: 'IMPORT ERROR',
        color: '#3498db'
      },
      export: {
        start: 'EXPORT STARTED',
        end: 'EXPORT COMPLETED',
        error: 'EXPORT ERROR',
        color: '#27ae60'
      },
      modify: {
        start: 'MODIFY STARTED',
        end: 'MODIFY COMPLETED',
        error: 'MODIFY ERROR',
        color: '#f39c12'
      },
      delete: {
        start: 'DELETE STARTED',
        end: 'DELETE COMPLETED',
        error: 'DELETE ERROR',
        color: '#e74c3c'
      },
      validation: {
        start: 'VALIDATION STARTED',
        end: 'VALIDATION COMPLETED',
        error: 'VALIDATION ERROR',
        color: '#9b59b6'
      },
      connection: {
        start: 'CONNECTION ESTABLISHED',
        end: 'CONNECTION CLOSED',
        error: 'CONNECTION ERROR',
        color: '#1abc9c'
      }
    };
  }
 
  /**
   * Format a message block with visual separators
   * @param {string} eventType - Type of event (import, export, etc.)
   * @param {string} eventStage - Stage of the event (start, end, error, progress)
   * @param {string} message - The main message
   * @param {Object} details - Additional details
   * @returns {string} Formatted message block
   */
  formatMessageBlock(eventType, eventStage, message) {
    let details = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    try {
      const eventConfig = this.eventTypes[eventType] || this.eventTypes.import;
      const timestamp = this.formatTimestamp(new Date());
      const separator = this.createSeparator();
      let formattedMessage = '';
 
      // Add separator at the beginning
      if (this.formattingOptions.showSeparators) {
        formattedMessage += separator + '\n';
      }
 
      // Add event marker
      if (this.formattingOptions.showEventMarkers) {
        const marker = this.getEventMarker(eventConfig, eventStage);
        formattedMessage += `${marker}\n`;
      }
 
      // Add timestamp
      if (this.formattingOptions.showTimestamps) {
        formattedMessage += `[${timestamp}] `;
      }
 
      // Add main message
      formattedMessage += message + '\n';
 
      // Add details if present
      if (details && Object.keys(details).length > 0) {
        formattedMessage += this.formatDetails(details);
      }
 
      // Add separator at the end
      if (this.formattingOptions.showSeparators) {
        formattedMessage += separator + '\n';
      }
      this.logger.debug('Message block formatted', {
        eventType,
        eventStage,
        messageLength: message.length
      });
      return formattedMessage;
    } catch (error) {
      this.logger.error('Error formatting message block', {
        error: error.message
      });
      return message; // Fallback to original message
    }
  }
 
  /**
   * Format a progress update message
   * @param {string} operation - Operation type
   * @param {number} current - Current progress
   * @param {number} total - Total items
   * @param {string} message - Progress message
   * @param {Object} stats - Progress statistics
   * @returns {string} Formatted progress message
   */
  formatProgressMessage(operation, current, total, message) {
    let stats = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
    try {
      const timestamp = this.formatTimestamp(new Date());
      const percentage = total > 0 ? Math.round(current / total * 100) : 0;
      let formattedMessage = '';
 
      // Add timestamp
      if (this.formattingOptions.showTimestamps) {
        formattedMessage += `[${timestamp}] `;
      }
 
      // Add progress indicator
      formattedMessage += `PROGRESS: ${current}/${total} (${percentage}%)`;
 
      // Add message if provided
      if (message) {
        formattedMessage += ` - ${message}`;
      }
 
      // Add stats if available
      if (stats && Object.keys(stats).length > 0) {
        formattedMessage += '\n' + this.formatProgressStats(stats);
      }
      return formattedMessage;
    } catch (error) {
      this.logger.error('Error formatting progress message', {
        error: error.message
      });
      return message || `Progress: ${current}/${total}`;
    }
  }
 
  /**
   * Format an error message with context
   * @param {string} operation - Operation type
   * @param {string} errorMessage - Error message
   * @param {Object} errorDetails - Error details
   * @returns {string} Formatted error message
   */
  formatErrorMessage(operation, errorMessage) {
    let errorDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    try {
      const eventConfig = this.eventTypes[operation] || this.eventTypes.import;
      const timestamp = this.formatTimestamp(new Date());
      const separator = this.createSeparator();
      let formattedMessage = '';
 
      // Add separator
      if (this.formattingOptions.showSeparators) {
        formattedMessage += separator + '\n';
      }
 
      // Add error marker
      formattedMessage += `${eventConfig.error}\n`;
 
      // Add timestamp and error message
      if (this.formattingOptions.showTimestamps) {
        formattedMessage += `[${timestamp}] `;
      }
      formattedMessage += `ERROR: ${errorMessage}\n`;
 
      // Add error details if present
      if (errorDetails && Object.keys(errorDetails).length > 0) {
        formattedMessage += this.formatErrorDetails(errorDetails);
      }
 
      // Add separator
      if (this.formattingOptions.showSeparators) {
        formattedMessage += separator + '\n';
      }
      return formattedMessage;
    } catch (error) {
      this.logger.error('Error formatting error message', {
        error: error.message
      });
      return `ERROR: ${errorMessage}`;
    }
  }
 
  /**
   * Format a completion message with results
   * @param {string} operation - Operation type
   * @param {Object} results - Operation results
   * @returns {string} Formatted completion message
   */
  formatCompletionMessage(operation) {
    let results = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    try {
      const eventConfig = this.eventTypes[operation] || this.eventTypes.import;
      const timestamp = this.formatTimestamp(new Date());
      const separator = this.createSeparator();
      let formattedMessage = '';
 
      // Add separator
      if (this.formattingOptions.showSeparators) {
        formattedMessage += separator + '\n';
      }
 
      // Add completion marker
      formattedMessage += `${eventConfig.end}\n`;
 
      // Add timestamp
      if (this.formattingOptions.showTimestamps) {
        formattedMessage += `[${timestamp}] `;
      }
 
      // Add completion message
      formattedMessage += `Operation completed successfully\n`;
 
      // Add results if present
      if (results && Object.keys(results).length > 0) {
        formattedMessage += this.formatResults(results);
      }
 
      // Add separator
      if (this.formattingOptions.showSeparators) {
        formattedMessage += separator + '\n';
      }
      return formattedMessage;
    } catch (error) {
      this.logger.error('Error formatting completion message', {
        error: error.message
      });
      return 'Operation completed successfully';
    }
  }
 
  /**
   * Format SSE event data for display
   * @param {Object} eventData - SSE event data
   * @returns {string} Formatted event message
   */
  formatSSEEvent(eventData) {
    try {
      const {
        type,
        message,
        current,
        total,
        counts,
        error
      } = eventData;
      const timestamp = this.formatTimestamp(new Date());
      let formattedMessage = '';
 
      // Add timestamp
      if (this.formattingOptions.showTimestamps) {
        formattedMessage += `[${timestamp}] `;
      }
 
      // Format based on event type
      switch (type) {
        case 'progress':
          formattedMessage += this.formatProgressMessage('import', current, total, message, counts);
          break;
        case 'completion':
          formattedMessage += this.formatCompletionMessage('import', eventData);
          break;
        case 'error':
          formattedMessage += this.formatErrorMessage('import', message, eventData);
          break;
        default:
          formattedMessage += `SSE EVENT [${type.toUpperCase()}]: ${message || 'No message'}`;
      }
      return formattedMessage;
    } catch (error) {
      this.logger.error('Error formatting SSE event', {
        error: error.message
      });
      return eventData.message || 'SSE event received';
    }
  }
 
  /**
   * Create a visual separator line
   * @returns {string} Separator string
   */
  createSeparator() {
    const char = this.formattingOptions.separatorChar;
    const length = this.formattingOptions.separatorLength;
    return char.repeat(length);
  }
 
  /**
   * Get event marker based on event type and stage
   * @param {Object} eventConfig - Event configuration
   * @param {string} stage - Event stage
   * @returns {string} Event marker
   */
  getEventMarker(eventConfig, stage) {
    switch (stage) {
      case 'start':
        return eventConfig.start;
      case 'end':
        return eventConfig.end;
      case 'error':
        return eventConfig.error;
      default:
        return eventConfig.start;
    }
  }
 
  /**
   * Format timestamp for display
   * @param {Date} date - Date to format
   * @returns {string} Formatted timestamp
   */
  formatTimestamp(date) {
    return date.toLocaleTimeString('en-US', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  }
 
  /**
   * Format details object for display
   * @param {Object} details - Details object
   * @returns {string} Formatted details
   */
  formatDetails(details) {
    try {
      let formatted = '';
      for (const [key, value] of Object.entries(details)) {
        if (value !== null && value !== undefined) {
          formatted += `  ${key}: ${value}\n`;
        }
      }
      return formatted;
    } catch (error) {
      this.logger.error('Error formatting details', {
        error: error.message
      });
      return '';
    }
  }
 
  /**
   * Format progress statistics
   * @param {Object} stats - Progress statistics
   * @returns {string} Formatted statistics
   */
  formatProgressStats(stats) {
    try {
      let formatted = '  Statistics:\n';
      const statLabels = {
        processed: 'Processed',
        success: 'Success',
        failed: 'Failed',
        skipped: 'Skipped',
        duplicates: 'Duplicates'
      };
      for (const [key, value] of Object.entries(stats)) {
        if (value !== null && value !== undefined && statLabels[key]) {
          formatted += `    ${statLabels[key]}: ${value}\n`;
        }
      }
      return formatted;
    } catch (error) {
      this.logger.error('Error formatting progress stats', {
        error: error.message
      });
      return '';
    }
  }
 
  /**
   * Format error details
   * @param {Object} errorDetails - Error details
   * @returns {string} Formatted error details
   */
  formatErrorDetails(errorDetails) {
    try {
      let formatted = '  Error Details:\n';
      for (const [key, value] of Object.entries(errorDetails)) {
        if (value !== null && value !== undefined) {
          formatted += `    ${key}: ${value}\n`;
        }
      }
      return formatted;
    } catch (error) {
      this.logger.error('Error formatting error details', {
        error: error.message
      });
      return '';
    }
  }
 
  /**
   * Format operation results
   * @param {Object} results - Operation results
   * @returns {string} Formatted results
   */
  formatResults(results) {
    try {
      let formatted = '  Results:\n';
      const resultLabels = {
        total: 'Total Records',
        success: 'Successful',
        failed: 'Failed',
        skipped: 'Skipped',
        duplicates: 'Duplicates',
        duration: 'Duration'
      };
      for (const [key, value] of Object.entries(results)) {
        if (value !== null && value !== undefined && resultLabels[key]) {
          let displayValue = value;
          if (key === 'duration' && typeof value === 'number') {
            displayValue = this.formatDuration(value);
          }
          formatted += `    ${resultLabels[key]}: ${displayValue}\n`;
        }
      }
      return formatted;
    } catch (error) {
      this.logger.error('Error formatting results', {
        error: error.message
      });
      return '';
    }
  }
 
  /**
   * Format duration in milliseconds to human readable format
   * @param {number} milliseconds - Duration in milliseconds
   * @returns {string} Formatted duration
   */
  formatDuration(milliseconds) {
    try {
      const seconds = Math.floor(milliseconds / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
      if (hours > 0) {
        return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
      } else if (minutes > 0) {
        return `${minutes}m ${seconds % 60}s`;
      } else {
        return `${seconds}s`;
      }
    } catch (error) {
      this.logger.error('Error formatting duration', {
        error: error.message
      });
      return `${milliseconds}ms`;
    }
  }
 
  /**
   * Update formatting options
   * @param {Object} options - New formatting options
   */
  updateFormattingOptions(options) {
    try {
      this.formattingOptions = {
        ...this.formattingOptions,
        ...options
      };
      this.logger.debug('Formatting options updated', {
        options
      });
    } catch (error) {
      this.logger.error('Error updating formatting options', {
        error: error.message
      });
    }
  }
 
  /**
   * Get current formatting options
   * @returns {Object} Current formatting options
   */
  getFormattingOptions() {
    return {
      ...this.formattingOptions
    };
  }
}
 
// Create and export singleton instance
exports.MessageFormatter = MessageFormatter;
const messageFormatter = exports.default = new MessageFormatter();
 
}).call(this)}).call(this,require('_process'))
},{"./winston-logger.js":70,"_process":29}],57:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.pingOneClient = exports.PingOneClient = void 0;
var _winstonLogger = require("./winston-logger.js");
var _uiManager = require("./ui-manager.js");
/**
 * @fileoverview PingOne Client Class
 * 
 * Handles authentication and API communication with PingOne services.
 * Manages token acquisition, caching, and API requests with Winston logging.
 * 
 * Features:
 * - Token management with localStorage caching
 * - Automatic token refresh
 * - API request handling with retry logic
 * - User import and modification operations
 * - Winston logging integration
 */
 
const ui = window.app && window.app.uiManager;
function handleClientError(error) {
  let userMessage = 'An unexpected error occurred. Please try again.';
  if (error && error.message) {
    if (error.message.includes('Network')) {
      userMessage = 'Network error – check your connection.';
    } else if (error.message.includes('timeout')) {
      userMessage = 'Request timed out – try again.';
    } else if (error.message.includes('401')) {
      userMessage = 'Session expired – please log in again.';
    } else if (error.message.includes('404')) {
      userMessage = 'Resource not found.';
    }
  }
  if (ui) ui.showStatusBar(userMessage, 'error');
}
 
/**
 * PingOne Client Class
 * 
 * Manages PingOne API authentication and requests with Winston logging.
 */
class PingOneClient {
  constructor() {
    // Initialize browser-compatible logger
    this.logger = {
      info: (msg, data) => console.log(`[PingOneClient] ${msg}`, data || ''),
      debug: (msg, data) => console.debug(`[PingOneClient] ${msg}`, data || ''),
      warn: (msg, data) => console.warn(`[PingOneClient] ${msg}`, data || ''),
      error: (msg, data) => console.error(`[PingOneClient] ${msg}`, data || '')
    };
    this.accessToken = null;
    this.tokenExpiry = null;
    this.baseUrl = '/api/pingone';
    this.initialize();
  }
 
  /**
   * Initialize the client
   */
  initialize() {
    try {
      this.loadTokenFromStorage();
      this.logger.info('PingOne client initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize PingOne client', {
        error: error.message
      });
    }
  }
 
  /**
   * Load token from localStorage
   */
  loadTokenFromStorage() {
    try {
      if (typeof localStorage !== 'undefined') {
        const storedToken = localStorage.getItem('pingone_worker_token');
        const storedExpiry = localStorage.getItem('pingone_token_expiry');
        if (storedToken && storedExpiry) {
          const expiryTime = parseInt(storedExpiry, 10);
          const now = Date.now();
          if (expiryTime > now) {
            this.accessToken = storedToken;
            this.tokenExpiry = expiryTime;
            this.logger.info('Token loaded from storage', {
              hasToken: !!this.accessToken,
              expiryTime: new Date(this.tokenExpiry).toISOString()
            });
          } else {
            this.logger.warn('Stored token has expired');
            this.clearToken();
          }
        } else {
          this.logger.debug('No stored token found');
        }
      } else {
        this.logger.warn('localStorage is not available');
      }
    } catch (error) {
      this.logger.error('Error loading token from storage', {
        error: error.message
      });
    }
  }
 
  /**
   * Save token to localStorage
   */
  saveTokenToStorage(token, expiresIn) {
    try {
      if (typeof localStorage !== 'undefined') {
        const expiryTime = Date.now() + expiresIn * 1000;
        localStorage.setItem('pingone_worker_token', token);
        localStorage.setItem('pingone_token_expiry', expiryTime.toString());
        this.accessToken = token;
        this.tokenExpiry = expiryTime;
        this.logger.info('Token saved to storage', {
          tokenLength: token.length,
          expiresIn,
          expiryTime: new Date(expiryTime).toISOString()
        });
        return true;
      } else {
        this.logger.warn('localStorage is not available, cannot save token');
        return false;
      }
    } catch (error) {
      this.logger.error('Error saving token to storage', {
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Clear token from storage
   */
  clearToken() {
    try {
      if (typeof localStorage !== 'undefined') {
        localStorage.removeItem('pingone_worker_token');
        localStorage.removeItem('pingone_token_expiry');
      }
      this.accessToken = null;
      this.tokenExpiry = null;
      this.logger.info('Token cleared from storage');
    } catch (error) {
      this.logger.error('Error clearing token from storage', {
        error: error.message
      });
    }
  }
 
  /**
   * Update credentials and clear existing token
   * @param {Object} credentials - New credentials object
   */
  updateCredentials(credentials) {
    try {
      this.logger.info('Updating PingOne client credentials');
 
      // Clear existing token since credentials are changing
      this.clearToken();
 
      // Store new credentials in localStorage
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem('pingone_credentials', JSON.stringify(credentials));
        this.logger.info('Credentials updated in localStorage');
      }
 
      // Trigger a custom event to notify other components
      window.dispatchEvent(new CustomEvent('credentials-updated', {
        detail: {
          credentials
        }
      }));
      this.logger.info('Credentials updated successfully');
    } catch (error) {
      this.logger.error('Error updating credentials', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Get cached token (alias for getCurrentTokenTimeRemaining for compatibility)
   * Production-ready with comprehensive error handling and validation
   */
  getCachedToken() {
    try {
      // Validate token existence and format
      if (!this.accessToken || typeof this.accessToken !== 'string') {
        this.logger.debug('No valid cached token available');
        return null;
      }
 
      // Validate expiry timestamp
      if (!this.tokenExpiry || typeof this.tokenExpiry !== 'number') {
        this.logger.warn('Invalid token expiry timestamp');
        this.clearToken(); // Clean up invalid state
        return null;
      }
      const now = Date.now();
      const isExpired = this.tokenExpiry <= now;
 
      // Add buffer time (5 minutes) to prevent edge cases
      const bufferTime = 5 * 60 * 1000; // 5 minutes in milliseconds
      const isNearExpiry = this.tokenExpiry - now <= bufferTime;
      if (isExpired) {
        this.logger.debug('Cached token is expired');
        this.clearToken(); // Clean up expired token
        return null;
      }
      if (isNearExpiry) {
        this.logger.warn('Token is near expiry, consider refreshing');
      }
 
      // Validate token format (basic JWT structure check)
      if (!this.accessToken.includes('.') || this.accessToken.split('.').length !== 3) {
        this.logger.error('Invalid token format detected');
        this.clearToken(); // Clean up invalid token
        return null;
      }
      this.logger.debug('Returning valid cached token');
      return this.accessToken;
    } catch (error) {
      this.logger.error('Error getting cached token', {
        error: error.message,
        stack: error.stack,
        tokenLength: this.accessToken ? this.accessToken.length : 0
      });
      // Don't expose token in logs for security
      return null;
    }
  }
 
  /**
   * Get current token time remaining
   */
  getCurrentTokenTimeRemaining() {
    try {
      if (!this.accessToken || !this.tokenExpiry) {
        return {
          token: null,
          timeRemaining: null,
          isExpired: true
        };
      }
      const now = Date.now();
      const timeRemaining = Math.max(0, this.tokenExpiry - now);
      const isExpired = timeRemaining === 0;
      const timeRemainingFormatted = this.formatDuration(Math.floor(timeRemaining / 1000));
 
      // Only log debug message every 5 minutes (300000ms) to reduce noise
      const lastLogTime = this.lastTokenTimeLog || 0;
      const timeSinceLastLog = now - lastLogTime;
      if (timeSinceLastLog >= 300000) {
        // 5 minutes
        this.logger.debug('Token time remaining calculated', {
          timeRemaining: timeRemainingFormatted,
          isExpired
        });
        this.lastTokenTimeLog = now;
      }
      return {
        token: this.accessToken,
        timeRemaining: timeRemainingFormatted,
        isExpired
      };
    } catch (error) {
      this.logger.error('Error getting token time remaining', {
        error: error.message
      });
      return {
        token: null,
        timeRemaining: null,
        isExpired: true
      };
    }
  }
 
  /**
   * Format duration in human-readable format
   */
  formatDuration(seconds) {
    if (seconds <= 0) return 'Expired';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor(seconds % 3600 / 60);
    const remainingSeconds = seconds % 60;
    if (hours > 0) {
      return `${hours}h ${minutes}m ${remainingSeconds}s`;
    } else if (minutes > 0) {
      return `${minutes}m ${remainingSeconds}s`;
    } else {
      return `${remainingSeconds}s`;
    }
  }
 
  /**
   * Get an access token using client credentials flow
   * @returns {Promise<string>} Access token
   */
  async getAccessToken() {
    try {
      this.logger.debug('getAccessToken called');
 
      // Check if we have a valid cached token
      const tokenInfo = this.getCurrentTokenTimeRemaining();
      if (tokenInfo.token && !tokenInfo.isExpired) {
        this.logger.debug('Using cached token', {
          tokenPreview: tokenInfo.token.substring(0, 8) + '...',
          timeRemaining: tokenInfo.timeRemaining
        });
        return tokenInfo.token;
      }
      this.logger.debug('Fetching token from /api/pingone/get-token');
 
      // Fetch new token from server
      const response = await fetch('/api/pingone/get-token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          // You can add additional parameters here if needed
          // useOverrideCredentials: false
        })
      });
      this.logger.debug('Fetch response', {
        status: response.status,
        ok: response.ok
      });
      if (!response.ok) {
        const errorMsg = await response.text();
        this.logger.error('Fetch error', {
          status: response.status,
          error: errorMsg
        });
        throw new Error(`Failed to get token: ${response.status} ${errorMsg}`);
      }
      const data = await response.json();
      this.logger.debug('Data received from server', {
        hasAccessToken: !!data.access_token,
        expiresIn: data.expires_in,
        success: data.success
      });
      if (!data.success) {
        this.logger.warn('Server returned error', {
          data
        });
        throw new Error(data.error || 'Failed to get token from server');
      }
      if (!data.access_token) {
        this.logger.warn('No access_token in server response', {
          data
        });
        throw new Error('No access token received from server');
      }
 
      // Save token to storage
      const tokenSaved = this.saveTokenToStorage(data.access_token, data.expires_in || 3600);
      if (tokenSaved) {
        this.logger.debug('Token saved to localStorage', {
          tokenLength: data.access_token.length,
          expiresIn: data.expires_in || 3600
        });
      } else {
        this.logger.warn('Failed to store token in localStorage');
      }
      return data.access_token;
    } catch (error) {
      this.logger.error('Error in getAccessToken', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Make authenticated API request with retry logic
   */
  async makeRequest(method, url) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    let retryAttempts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 3;
    try {
      const token = await this.getAccessToken();
      for (let attempt = 1; attempt <= retryAttempts; attempt++) {
        try {
          this.logger.debug(`Making API request (attempt ${attempt})`, {
            method,
            url,
            hasData: !!data
          });
          const requestOptions = {
            method,
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            }
          };
          if (data) {
            requestOptions.body = JSON.stringify(data);
          }
          const response = await fetch(`${this.baseUrl}${url}`, requestOptions);
          this.logger.debug(`API request completed (attempt ${attempt})`, {
            status: response.status,
            ok: response.ok
          });
          if (response.ok) {
            const responseData = await response.json();
            return responseData;
          } else {
            const errorText = await response.text();
            this.logger.warn(`API request failed (attempt ${attempt})`, {
              status: response.status,
              error: errorText
            });
            if (attempt === retryAttempts) {
              throw new Error(`API request failed: ${response.status} ${errorText}`);
            }
          }
        } catch (error) {
          this.logger.error(`API request error (attempt ${attempt})`, {
            error: error.message
          });
          if (attempt === retryAttempts) {
            throw error;
          }
 
          // Wait before retry
          await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
        }
      }
    } catch (error) {
      this.logger.error('All API request attempts failed', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Get populations from PingOne API
   */
  async getPopulations() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    try {
      this.logger.info('Getting populations from PingOne API');
      const url = '/api/pingone/populations';
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      if (!response.ok) {
        throw new Error(`Failed to fetch populations: ${response.status} ${response.statusText}`);
      }
      return response;
    } catch (error) {
      this.logger.error('Failed to get populations', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Import users from CSV data
   */
  async importUsers(csvData) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    try {
      this.logger.info('importUsers method called', {
        userCount: csvData.length,
        options: Object.keys(options)
      });
      const {
        populationId = null,
        batchSize = 10,
        retryAttempts = 3,
        enableUsers = true,
        skipDuplicatesByEmail = false,
        skipDuplicatesByUsername = false
      } = options;
      this.logger.debug('Initial setup completed', {
        batchSize,
        retryAttempts,
        enableUsers,
        skipDuplicatesByEmail,
        skipDuplicatesByUsername
      });
 
      // Validate input
      if (!csvData || !Array.isArray(csvData) || csvData.length === 0) {
        throw new Error('Invalid CSV data: must be a non-empty array');
      }
      this.logger.debug('Input validation completed');
 
      // Handle population selection
      let fallbackPopulationId = populationId;
      if (!fallbackPopulationId) {
        const populationSelect = document.getElementById('import-population-select');
        if (populationSelect && populationSelect.value) {
          fallbackPopulationId = populationSelect.value;
          this.logger.debug('Using selected population from dropdown', {
            fallbackPopulationId
          });
        } else {
          // Try to get from settings
          const settings = JSON.parse(localStorage.getItem('pingone-import-settings') || '{}');
          fallbackPopulationId = settings.populationId;
          this.logger.debug('Using default population from settings', {
            fallbackPopulationId
          });
        }
      }
 
      // Prepare sets for duplicate detection
      const seenEmails = new Set();
      const seenUsernames = new Set();
 
      // Process users in batches
      const totalUsers = csvData.length;
      const results = {
        success: true,
        processed: 0,
        created: 0,
        skipped: 0,
        failed: 0,
        errors: []
      };
      this.logger.debug('Starting user processing loop...');
      for (let i = 0; i < totalUsers; i += batchSize) {
        const batch = csvData.slice(i, i + batchSize);
        this.logger.debug(`Processing batch ${Math.floor(i / batchSize) + 1}`, {
          users: `${i + 1}-${Math.min(i + batchSize, totalUsers)}`,
          batchSize: batch.length
        });
        for (const user of batch) {
          try {
            const userPopulationId = user.populationId || fallbackPopulationId;
            if (!userPopulationId) {
              const error = `Missing population – user not processed. Username: ${user.email || user.username}`;
              results.errors.push(error);
              results.skipped++;
              continue;
            }
 
            // Duplicate detection
            if (skipDuplicatesByEmail && user.email) {
              if (seenEmails.has(user.email.toLowerCase())) {
                this.logger.info(`Skipping duplicate user by email: ${user.email}`);
                results.skipped++;
                continue;
              }
              seenEmails.add(user.email.toLowerCase());
            }
            if (skipDuplicatesByUsername && user.username) {
              if (seenUsernames.has(user.username.toLowerCase())) {
                this.logger.info(`Skipping duplicate user by username: ${user.username}`);
                results.skipped++;
                continue;
              }
              seenUsernames.add(user.username.toLowerCase());
            }
 
            // Create user
            const userData = {
              username: user.username || user.email,
              email: user.email,
              name: {
                given: user.firstName || user.givenName || '',
                family: user.lastName || user.familyName || ''
              },
              enabled: enableUsers,
              population: {
                id: userPopulationId
              }
            };
 
            // Add optional fields
            if (user.phoneNumber) userData.phoneNumber = user.phoneNumber;
            if (user.company) userData.company = user.company;
            const result = await this.createUser(userData, retryAttempts);
            if (result.success) {
              results.created++;
              // Disable user if requested
              if (!enableUsers && result.userId) {
                this.logger.debug(`Disabling user ${result.userId} after creation`);
                try {
                  await this.makeRequest('PATCH', `/environments/current/users/${result.userId}`, {
                    enabled: false
                  });
                  this.logger.debug(`Successfully disabled user ${result.userId}`);
                } catch (statusError) {
                  this.logger.warn(`Failed to disable user ${result.userId}`, {
                    error: statusError.message
                  });
                }
              }
            } else {
              results.failed++;
              results.errors.push(result.error);
            }
            results.processed++;
          } catch (error) {
            results.failed++;
            results.errors.push(error.message);
          }
        }
      }
      this.logger.info('Batch import summary', {
        total: totalUsers,
        processed: results.processed,
        created: results.created,
        skipped: results.skipped,
        failed: results.failed
      });
      return results;
    } catch (error) {
      this.logger.error('Import users failed', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Create a single user
   */
  async createUser(userData) {
    let retryAttempts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
    try {
      for (let attempt = 1; attempt <= retryAttempts; attempt++) {
        try {
          this.logger.debug(`Making API request for user ${userData.email || userData.username} (attempt ${attempt}/${retryAttempts})`);
          const result = await this.makeRequest('POST', '/environments/current/users', userData);
          this.logger.debug(`API request completed for user ${userData.email || userData.username}`);
          if (result.id) {
            const successMessage = `Successfully created user: ${userData.username || userData.email}`;
            this.logger.info(successMessage, {
              userId: result.id,
              populationId: userData.population.id
            });
            return {
              success: true,
              userId: result.id,
              user: result
            };
          } else {
            this.logger.warn('Invalid response structure - no ID found', {
              result
            });
            return {
              success: false,
              error: 'Invalid response structure'
            };
          }
        } catch (error) {
          if (error.message.includes('already exists')) {
            this.logger.debug(`User already exists: ${userData.email || userData.username}`);
            return {
              success: true,
              userId: null,
              user: null,
              message: 'User already exists'
            };
          }
          this.logger.error(`API request failed for user ${userData.email || userData.username} (attempt ${attempt})`, {
            error: error.message
          });
          if (attempt === retryAttempts) {
            return {
              success: false,
              error: error.message
            };
          }
 
          // Wait before retry
          await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
        }
      }
    } catch (error) {
      this.logger.error('Create user failed', {
        error: error.message,
        userData
      });
      return {
        success: false,
        error: error.message
      };
    }
  }
}
 
// Create and export default instance
exports.PingOneClient = PingOneClient;
const pingOneClient = exports.pingOneClient = new PingOneClient();
 
// Export the class and instance
 
},{"./ui-manager.js":68,"./winston-logger.js":70}],58:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.PopulationSubsystem = void 0;
/**
 * Population Subsystem
 * Centralized population management system for dropdown handling and population operations
 * Provides population loading, caching, filtering, and event integration
 */
 
class PopulationSubsystem {
  constructor(eventBus, settingsSubsystem, loggingSubsystem, apiClient) {
    this.eventBus = eventBus;
    this.settingsSubsystem = settingsSubsystem;
    this.loggingSubsystem = loggingSubsystem;
    this.apiClient = apiClient;
 
    // Population cache
    this.populationCache = new Map();
    this.cacheExpiry = 5 * 60 * 1000; // 5 minutes
    this.lastCacheUpdate = null;
 
    // Population loading state
    this.isLoading = false;
    this.loadingPromise = null;
 
    // Dropdown management
    this.managedDropdowns = new Set();
    this.dropdownConfigs = new Map();
 
    // Initialize subsystem
    this.init();
    if (this.loggingSubsystem) {
      this.loggingSubsystem.info('PopulationSubsystem initialized successfully', {}, 'system');
    }
  }
 
  /**
   * Initialize the population subsystem
   */
  async init() {
    try {
      // Set up event listeners
      this.setupEventListeners();
 
      // Load cached populations if available
      this.loadCachedPopulations();
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info('PopulationSubsystem initialization complete', {
          cachedPopulations: this.populationCache.size
        }, 'system');
      }
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to initialize PopulationSubsystem', error, 'system');
      }
      throw error;
    }
  }
 
  /**
   * Set up event listeners for cross-subsystem communication
   */
  setupEventListeners() {
    if (this.eventBus) {
      // Listen for settings changes that might affect populations
      this.eventBus.on('settingsChanged', () => {
        this.invalidateCache();
      });
 
      // Listen for authentication events
      this.eventBus.on('authenticationSuccess', () => {
        this.refreshPopulations();
      });
      this.eventBus.on('authenticationFailed', () => {
        this.clearCache();
      });
 
      // Listen for population refresh requests
      this.eventBus.on('refreshPopulations', data => {
        this.refreshPopulations(data.force);
      });
 
      // Listen for dropdown registration
      this.eventBus.on('registerDropdown', data => {
        this.registerDropdown(data.dropdownId, data.config);
      });
    }
  }
 
  /**
   * Load populations from API with caching
   */
  async loadPopulations() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      force = false,
      useCache = true
    } = options;
    try {
      // Check cache first if not forcing refresh
      if (!force && useCache && this.isCacheValid()) {
        const cached = this.getCachedPopulations();
        if (cached && cached.length > 0) {
          if (this.loggingSubsystem) {
            this.loggingSubsystem.debug('Returning cached populations', {
              count: cached.length
            }, 'system');
          }
          return cached;
        }
      }
 
      // Prevent multiple simultaneous loads
      if (this.isLoading && this.loadingPromise) {
        return await this.loadingPromise;
      }
      this.isLoading = true;
      this.loadingPromise = this.performPopulationLoad();
      const populations = await this.loadingPromise;
 
      // Cache the results
      this.cachePopulations(populations);
 
      // Emit event for UI updates
      if (this.eventBus) {
        this.eventBus.emit('populationsLoaded', {
          populations,
          count: populations.length,
          cached: false
        });
      }
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info('Populations loaded successfully', {
          count: populations.length
        }, 'system');
      }
      return populations;
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to load populations', error, 'system');
      }
 
      // Emit error event
      if (this.eventBus) {
        this.eventBus.emit('populationsLoadFailed', {
          error: error.message
        });
      }
      throw error;
    } finally {
      this.isLoading = false;
      this.loadingPromise = null;
    }
  }
 
  /**
   * Perform the actual population loading from API
   */
  async performPopulationLoad() {
    if (this.loggingSubsystem) {
      this.loggingSubsystem.debug('Starting performPopulationLoad', {}, 'system');
    }
    if (!this.apiClient) {
      const error = 'API client not available for population loading';
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error(error, {}, 'system');
      }
      throw new Error(error);
    }
 
    // Check if API client has the required method
    if (typeof this.apiClient.get !== 'function') {
      const error = 'API client does not support HTTP GET requests';
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error(error, {
          apiClientType: typeof this.apiClient
        }, 'system');
      }
      throw new Error(error);
    }
    if (this.loggingSubsystem) {
      this.loggingSubsystem.debug('Making API call to /api/populations', {}, 'system');
    }
    try {
      // Load populations from API using the /api/populations endpoint
      const response = await this.apiClient.get('/api/populations');
      if (this.loggingSubsystem) {
        this.loggingSubsystem.debug('API response received', {
          hasResponse: !!response,
          hasPopulations: !!(response && response.populations),
          populationsIsArray: !!(response && Array.isArray(response.populations)),
          populationCount: response && response.populations ? response.populations.length : 0
        }, 'system');
      }
      if (!response || !Array.isArray(response.populations)) {
        const error = 'Invalid populations response from API';
        if (this.loggingSubsystem) {
          this.loggingSubsystem.error(error, {
            response
          }, 'system');
        }
        throw new Error(error);
      }
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info(`Successfully loaded ${response.populations.length} populations from API`, {}, 'system');
      }
      return response.populations;
    } catch (apiError) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('API call to /api/populations failed', {
          error: apiError.message,
          stack: apiError.stack
        }, 'system');
      }
      throw apiError;
    }
  }
 
  /**
   * Populate a dropdown with populations
   */
  async populateDropdown(dropdownId) {
    let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    try {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.debug(`Starting population dropdown population for: ${dropdownId}`, config, 'system');
      }
      const {
        includeEmpty = true,
        emptyText = 'Select a population',
        emptyValue = '',
        filter = null,
        sortBy = 'name',
        sortOrder = 'asc'
      } = config;
 
      // Register dropdown for management
      this.registerDropdown(dropdownId, config);
      const dropdown = document.getElementById(dropdownId);
      if (!dropdown) {
        const error = `Dropdown element not found: ${dropdownId}`;
        if (this.loggingSubsystem) {
          this.loggingSubsystem.error(error, {}, 'system');
        }
        throw new Error(error);
      }
      if (this.loggingSubsystem) {
        this.loggingSubsystem.debug(`Dropdown element found, showing loading state for: ${dropdownId}`, {}, 'system');
      }
 
      // Show loading state
      this.showDropdownLoading(dropdown);
      if (this.loggingSubsystem) {
        this.loggingSubsystem.debug(`Loading populations for dropdown: ${dropdownId}`, {}, 'system');
      }
 
      // Load populations
      const populations = await this.loadPopulations();
 
      // Filter populations if needed
      let filteredPopulations = populations;
      if (filter && typeof filter === 'function') {
        filteredPopulations = populations.filter(filter);
      }
 
      // Sort populations
      filteredPopulations = this.sortPopulations(filteredPopulations, sortBy, sortOrder);
 
      // Clear existing options
      dropdown.innerHTML = '';
 
      // Add empty option if requested
      if (includeEmpty) {
        const emptyOption = document.createElement('option');
        emptyOption.value = emptyValue;
        emptyOption.textContent = emptyText;
        dropdown.appendChild(emptyOption);
      }
 
      // Add population options
      filteredPopulations.forEach(population => {
        const option = document.createElement('option');
        option.value = population.id;
        option.textContent = population.name;
        option.dataset.populationId = population.id;
        option.dataset.populationName = population.name;
        dropdown.appendChild(option);
      });
 
      // Hide loading state
      this.hideDropdownLoading(dropdown);
 
      // Emit event for UI updates
      if (this.eventBus) {
        this.eventBus.emit('dropdownPopulated', {
          dropdownId,
          populationCount: filteredPopulations.length
        });
      }
      if (this.loggingSubsystem) {
        this.loggingSubsystem.debug('Dropdown populated successfully', {
          dropdownId,
          populationCount: filteredPopulations.length
        }, 'system');
      }
      return true;
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to populate dropdown', {
          dropdownId,
          error: error.message
        }, 'system');
      }
 
      // Show error state in dropdown
      this.showDropdownError(dropdownId, error.message);
 
      // Emit error event
      if (this.eventBus) {
        this.eventBus.emit('dropdownPopulationFailed', {
          dropdownId,
          error: error.message
        });
      }
      return false;
    }
  }
 
  /**
   * Register a dropdown for management
   */
  registerDropdown(dropdownId) {
    let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.managedDropdowns.add(dropdownId);
    this.dropdownConfigs.set(dropdownId, config);
    if (this.loggingSubsystem) {
      this.loggingSubsystem.debug('Dropdown registered', {
        dropdownId
      }, 'system');
    }
  }
 
  /**
   * Refresh all managed dropdowns
   */
  async refreshAllDropdowns() {
    try {
      const refreshPromises = Array.from(this.managedDropdowns).map(dropdownId => {
        const config = this.dropdownConfigs.get(dropdownId) || {};
        return this.populateDropdown(dropdownId, config);
      });
      await Promise.all(refreshPromises);
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info('All dropdowns refreshed', {
          count: this.managedDropdowns.size
        }, 'system');
      }
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to refresh all dropdowns', error, 'system');
      }
    }
  }
 
  /**
   * Refresh populations and update all dropdowns
   */
  async refreshPopulations() {
    let force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    try {
      // Load fresh populations
      await this.loadPopulations({
        force: true
      });
 
      // Refresh all managed dropdowns
      await this.refreshAllDropdowns();
      if (this.loggingSubsystem) {
        this.loggingSubsystem.info('Populations refreshed successfully', {}, 'system');
      }
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to refresh populations', error, 'system');
      }
    }
  }
 
  /**
   * Sort populations by specified criteria
   */
  sortPopulations(populations) {
    let sortBy = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'name';
    let sortOrder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'asc';
    return populations.sort((a, b) => {
      let aValue = a[sortBy];
      let bValue = b[sortBy];
 
      // Handle string comparison
      if (typeof aValue === 'string' && typeof bValue === 'string') {
        aValue = aValue.toLowerCase();
        bValue = bValue.toLowerCase();
      }
      let comparison = 0;
      if (aValue < bValue) {
        comparison = -1;
      } else if (aValue > bValue) {
        comparison = 1;
      }
      return sortOrder === 'desc' ? -comparison : comparison;
    });
  }
 
  /**
   * Show loading state for dropdown
   */
  showDropdownLoading(dropdown) {
    dropdown.innerHTML = '<option value="">Loading populations...</option>';
    dropdown.disabled = true;
    dropdown.classList.add('loading');
  }
 
  /**
   * Hide loading state for dropdown
   */
  hideDropdownLoading(dropdown) {
    dropdown.disabled = false;
    dropdown.classList.remove('loading');
  }
 
  /**
   * Show error state for dropdown
   */
  showDropdownError(dropdownId, errorMessage) {
    const dropdown = document.getElementById(dropdownId);
    if (dropdown) {
      dropdown.innerHTML = `<option value="">Error: ${errorMessage}</option>`;
      dropdown.disabled = false;
      dropdown.classList.add('error');
    }
  }
 
  /**
   * Cache populations with timestamp
   */
  cachePopulations(populations) {
    this.populationCache.set('populations', populations);
    this.lastCacheUpdate = Date.now();
 
    // Save to localStorage for persistence
    try {
      localStorage.setItem('pingone-populations-cache', JSON.stringify({
        populations,
        timestamp: this.lastCacheUpdate
      }));
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.warn('Failed to save populations to localStorage', error, 'system');
      }
    }
  }
 
  /**
   * Get cached populations
   */
  getCachedPopulations() {
    return this.populationCache.get('populations') || [];
  }
 
  /**
   * Check if cache is valid
   */
  isCacheValid() {
    if (!this.lastCacheUpdate) {
      return false;
    }
    const age = Date.now() - this.lastCacheUpdate;
    return age < this.cacheExpiry;
  }
 
  /**
   * Load cached populations from localStorage
   */
  loadCachedPopulations() {
    try {
      const cached = localStorage.getItem('pingone-populations-cache');
      if (cached) {
        const {
          populations,
          timestamp
        } = JSON.parse(cached);
 
        // Check if cache is still valid
        const age = Date.now() - timestamp;
        if (age < this.cacheExpiry) {
          this.populationCache.set('populations', populations);
          this.lastCacheUpdate = timestamp;
          if (this.loggingSubsystem) {
            this.loggingSubsystem.debug('Loaded populations from localStorage cache', {
              count: populations.length,
              age: Math.round(age / 1000)
            }, 'system');
          }
        }
      }
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.warn('Failed to load populations from localStorage', error, 'system');
      }
    }
  }
 
  /**
   * Invalidate cache
   */
  invalidateCache() {
    this.populationCache.clear();
    this.lastCacheUpdate = null;
 
    // Clear localStorage cache
    try {
      localStorage.removeItem('pingone-populations-cache');
    } catch (error) {
      // Ignore localStorage errors
    }
    if (this.loggingSubsystem) {
      this.loggingSubsystem.debug('Population cache invalidated', {}, 'system');
    }
  }
 
  /**
   * Clear cache completely
   */
  clearCache() {
    this.invalidateCache();
    if (this.loggingSubsystem) {
      this.loggingSubsystem.debug('Population cache cleared', {}, 'system');
    }
  }
 
  /**
   * Get population by ID
   */
  async getPopulationById(populationId) {
    try {
      const populations = await this.loadPopulations();
      return populations.find(pop => pop.id === populationId) || null;
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to get population by ID', {
          populationId,
          error: error.message
        }, 'system');
      }
      return null;
    }
  }
 
  /**
   * Search populations by name
   */
  async searchPopulations(searchTerm) {
    try {
      const populations = await this.loadPopulations();
      const searchLower = searchTerm.toLowerCase();
      return populations.filter(pop => pop.name.toLowerCase().includes(searchLower) || pop.description && pop.description.toLowerCase().includes(searchLower));
    } catch (error) {
      if (this.loggingSubsystem) {
        this.loggingSubsystem.error('Failed to search populations', {
          searchTerm,
          error: error.message
        }, 'system');
      }
      return [];
    }
  }
 
  /**
   * Get cache statistics
   */
  getCacheStats() {
    return {
      isValid: this.isCacheValid(),
      lastUpdate: this.lastCacheUpdate,
      age: this.lastCacheUpdate ? Date.now() - this.lastCacheUpdate : null,
      populationCount: this.getCachedPopulations().length,
      managedDropdowns: this.managedDropdowns.size
    };
  }
}
 
// Export for use in other modules
exports.PopulationSubsystem = PopulationSubsystem;
var _default = exports.default = PopulationSubsystem;
 
},{}],59:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.ProgressManager = void 0;
var _winstonLogger = require("./winston-logger.js");
var _elementRegistry = require("./element-registry.js");
var _sessionManager = require("./session-manager.js");
var _messageFormatter = _interopRequireDefault(require("./message-formatter.js"));
/**
 * Enhanced Progress Manager Module
 * 
 * Modern, real-time progress UI system with Socket.IO and WebSocket fallback:
 * - Real-time updates via Socket.IO (primary)
 * - WebSocket fallback for reliability
 * - Professional Ping Identity design system
 * - Responsive and accessible
 * - Enhanced visual feedback
 * - Step-by-step progress tracking
 * 
 * Features:
 * - Real-time progress updates via Socket.IO
 * - WebSocket fallback for connection issues
 * - Professional progress indicators
 * - Step-by-step operation tracking
 * - Enhanced error handling and recovery
 * - Accessibility compliance
 * - Production-ready logging
 */
 
// Enable debug mode for development (set to false in production)
const DEBUG_MODE = process.env.NODE_ENV !== 'production';
 
/**
 * Enhanced Progress Manager Class
 * 
 * Manages all progress-related UI updates with real-time Socket.IO and WebSocket integration
 */
class ProgressManager {
  constructor() {
    this.logger = (0, _winstonLogger.createWinstonLogger)('pingone-progress');
    this.isEnabled = true; // Will be set to false if progress container is not found
    this.currentOperation = null;
    this.currentSessionId = null;
    this.isActive = false;
    this.startTime = null;
    this.timingInterval = null;
    this.progressCallback = null;
    this.completeCallback = null;
    this.cancelCallback = null;
    this.duplicateHandlingMode = 'skip';
 
    // Real-time communication
    this.socket = null;
    this.websocket = null;
    this.connectionType = null; // 'socketio' or 'websocket'
    this.connectionRetries = 0;
    this.maxRetries = 3;
 
    // Stats tracking
    this.stats = {
      processed: 0,
      success: 0,
      failed: 0,
      skipped: 0,
      total: 0
    };
    this.logger.debug('ProgressManager initialized');
  }
 
  /**
   * Initialize the progress manager and setup core functionality
   */
  initialize() {
    try {
      this.setupElements();
      this.setupEventListeners();
      this.logger.info('Enhanced progress manager initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize progress manager', {
        error: error.message
      });
    }
  }
 
  /**
   * Setup DOM elements with enhanced design
   */
  setupElements() {
    try {
      // Main progress container - use existing one from HTML or find operation-specific container
      this.progressContainer = document.getElementById('progress-container');
 
      // If main container not found, we'll dynamically select the appropriate container based on operation
      if (!this.progressContainer) {
        this.logger.info('Main progress container not found - will use operation-specific containers');
        // We'll set isEnabled to true since we'll find the container dynamically when needed
        this.isEnabled = true;
      }
 
      // Log the progress container details for debugging
      this.logger.info('Progress container found', {
        id: this.progressContainer.id,
        className: this.progressContainer.className,
        display: this.progressContainer.style.display,
        visibility: this.progressContainer.style.visibility,
        offsetParent: this.progressContainer.offsetParent !== null
      });
 
      // Create enhanced progress content
      this.progressContainer.innerHTML = `
                <div class="progress-overlay">
                    <div class="progress-modal">
                        <div class="progress-header">
                            <div class="operation-info">
                                <h3 class="operation-title">
                                    <i class="fas fa-cog fa-spin"></i>
                                    <span class="title-text">Operation in Progress</span>
                                </h3>
                                <div class="operation-subtitle">Processing your request...</div>
                            </div>
                            <button class="cancel-operation" type="button" aria-label="Cancel operation">
                                <i class="fas fa-times"></i>
                                <span>Cancel</span>
                            </button>
                        </div>
                        
                        <div class="progress-content">
                            <div class="progress-steps">
                                <div class="step active" data-step="init">
                                    <div class="step-icon">
                                        <i class="fas fa-play"></i>
                                    </div>
                                    <div class="step-label">Initializing</div>
                                </div>
                                <div class="step" data-step="validate">
                                    <div class="step-icon">
                                        <i class="fas fa-check"></i>
                                    </div>
                                    <div class="step-label">Validating</div>
                                </div>
                                <div class="step" data-step="process">
                                    <div class="step-icon">
                                        <i class="fas fa-cogs"></i>
                                    </div>
                                    <div class="step-label">Processing</div>
                                </div>
                                <div class="step" data-step="complete">
                                    <div class="step-icon">
                                        <i class="fas fa-check-circle"></i>
                                    </div>
                                    <div class="step-label">Complete</div>
                                </div>
                            </div>
                            
                            <div class="progress-main">
                                <div class="progress-bar-container">
                                    <div class="progress-bar">
                                        <div class="progress-bar-fill"></div>
                                        <div class="progress-bar-glow"></div>
                                    </div>
                                    <div class="progress-percentage">0%</div>
                                </div>
                                
                                <div class="progress-text">Preparing operation...</div>
                                
                                <div class="progress-stats">
                                    <div class="stat-item">
                                        <span class="stat-label">Processed:</span>
                                        <span class="stat-value processed">0</span>
                                    </div>
                                    <div class="stat-item">
                                        <span class="stat-label">Success:</span>
                                        <span class="stat-value success">0</span>
                                    </div>
                                    <div class="stat-item">
                                        <span class="stat-label">Failed:</span>
                                        <span class="stat-value failed">0</span>
                                    </div>
                                    <div class="stat-item">
                                        <span class="stat-label">Skipped:</span>
                                        <span class="stat-value skipped">0</span>
                                    </div>
                                </div>
                                
                                <div class="progress-timing">
                                    <div class="time-elapsed">
                                        <i class="fas fa-clock"></i>
                                        <span>Time: <span class="elapsed-value">00:00</span></span>
                                    </div>
                                    <div class="time-remaining">
                                        <i class="fas fa-hourglass-half"></i>
                                        <span>ETA: <span class="eta-value">Calculating...</span></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="progress-details">
                                <div class="details-header">
                                    <h4><i class="fas fa-info-circle"></i> Operation Details</h4>
                                </div>
                                <div class="details-content">
                                    <div class="detail-item">
                                        <span class="detail-label">Operation Type:</span>
                                        <span class="detail-value operation-type">-</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">Session ID:</span>
                                        <span class="detail-value session-id">-</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">Population:</span>
                                        <span class="detail-value population-info">-</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">Connection:</span>
                                        <span class="detail-value connection-type">-</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
      this.logger.debug('Progress elements setup completed');
    } catch (error) {
      this.logger.error('Error setting up progress elements', {
        error: error.message
      });
      this.isEnabled = false;
    }
  }
 
  /**
   * Setup event listeners for progress interactions
   */
  setupEventListeners() {
    if (!this.isEnabled) {
      this.logger.warn('Progress manager not enabled - skipping event listener setup');
      return;
    }
    try {
      // Cancel operation button
      const cancelButton = this.progressContainer.querySelector('.cancel-operation');
      if (cancelButton) {
        cancelButton.addEventListener('click', () => this.cancelOperation());
      }
 
      // Close progress button (if exists)
      const closeButton = this.progressContainer.querySelector('.close-progress-btn');
      if (closeButton) {
        closeButton.addEventListener('click', () => this.hideProgress());
      }
      this.logger.debug('Progress event listeners setup completed');
    } catch (error) {
      this.logger.error('Error setting up progress event listeners', {
        error: error.message
      });
    }
  }
 
  /**
   * Start a new operation with progress tracking
   * @param {string} operationType - Type of operation (import, export, delete, modify)
   * @param {Object} options - Operation options
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   * @param {string} options.populationId - Population ID
   */
  startOperation(operationType) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    if (!this.isEnabled) {
      this.logger.warn('Progress manager not enabled - cannot start operation');
      return;
    }
    this.currentOperation = operationType;
    this.isActive = true;
    this.startTime = Date.now();
    this.resetOperationStats();
 
    // Select the appropriate progress container based on operation type
    this.selectProgressContainer(operationType);
 
    // If we still don't have a progress container, try to create one
    if (!this.progressContainer) {
      this.createFallbackProgressContainer(operationType);
    }
 
    // If we still don't have a container, we can't proceed
    if (!this.progressContainer) {
      this.logger.error('No progress container available for operation', {
        operationType
      });
      return;
    }
 
    // Initialize the progress container with content if needed
    this.initializeProgressContainer();
 
    // Update operation details
    this.updateOperationTitle(operationType);
    this.updateOperationDetails(options);
 
    // Show progress
    this.showProgress();
 
    // Start timing updates
    this.startTimingUpdates();
    this.logger.info('Operation started', {
      operationType,
      options
    });
  }
 
  /**
   * Select the appropriate progress container based on operation type
   * @param {string} operationType - Type of operation (import, export, delete, modify)
   */
  selectProgressContainer(operationType) {
    // If we already have a container, keep using it
    if (this.progressContainer && this.progressContainer.parentNode) {
      return;
    }
 
    // Try to find operation-specific container first
    const containerMap = {
      'import': 'progress-container',
      'delete': 'progress-container-delete',
      'modify': 'progress-container-modify',
      'export': 'progress-container-export'
    };
    const containerId = containerMap[operationType] || 'progress-container';
    this.progressContainer = document.getElementById(containerId);
 
    // If not found, try the main progress container
    if (!this.progressContainer) {
      this.progressContainer = document.getElementById('progress-container');
    }
 
    // Log what we found
    if (this.progressContainer) {
      this.logger.info('Selected progress container', {
        id: this.progressContainer.id,
        operationType
      });
    } else {
      this.logger.warn('No progress container found for operation', {
        operationType
      });
    }
  }
 
  /**
   * Create a fallback progress container if none exists
   * @param {string} operationType - Type of operation
   */
  createFallbackProgressContainer(operationType) {
    try {
      // Create a simple progress container
      const fallbackContainer = document.createElement('div');
      fallbackContainer.id = 'progress-container-fallback';
      fallbackContainer.className = 'progress-container visible';
      fallbackContainer.style.cssText = `
                display: block !important;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.7);
                z-index: 10000;
                display: flex;
                justify-content: center;
                align-items: center;
            `;
 
      // Add to the document
      document.body.appendChild(fallbackContainer);
      this.progressContainer = fallbackContainer;
      this.logger.info('Created fallback progress container', {
        operationType
      });
    } catch (error) {
      this.logger.error('Failed to create fallback progress container', {
        error: error.message
      });
    }
  }
 
  /**
   * Initialize the progress container with content if needed
   */
  initializeProgressContainer() {
    // Only initialize if the container is empty
    if (this.progressContainer && !this.progressContainer.querySelector('.progress-overlay')) {
      this.setupElements();
      this.setupEventListeners();
    }
  }
 
  /**
   * Initialize real-time connection for progress updates
   * @param {string} sessionId - Session ID for tracking
   */
  initializeRealTimeConnection(sessionId) {
    if (!sessionId) {
      this.logger.warn('No session ID provided for real-time connection');
      return;
    }
    this.currentSessionId = sessionId;
    this.connectionRetries = 0;
 
    // Try Socket.IO first, then fallback to WebSocket
    this.trySocketIOConnection(sessionId);
  }
 
  /**
   * Try Socket.IO connection for real-time updates
   * @param {string} sessionId - Session ID for tracking
   */
  trySocketIOConnection(sessionId) {
    try {
      // Check if Socket.IO is already loaded globally
      if (typeof io !== 'undefined') {
        this.logger.info('Using global Socket.IO client');
        this.connectWithSocketIO(io, sessionId);
      } else {
        // Try to load Socket.IO dynamically
        this.logger.info('Loading Socket.IO client dynamically');
 
        // Create a script element to load Socket.IO
        const script = document.createElement('script');
        script.src = '/socket.io/socket.io.js';
        script.async = true;
        script.onload = () => {
          this.logger.info('Socket.IO client loaded successfully');
          if (typeof io !== 'undefined') {
            this.connectWithSocketIO(io, sessionId);
          } else {
            this.logger.warn('Socket.IO loaded but io is undefined, trying WebSocket');
            this.tryWebSocketConnection(sessionId);
          }
        };
        script.onerror = error => {
          this.logger.warn('Failed to load Socket.IO client script', {
            error: error.message
          });
          this.tryWebSocketConnection(sessionId);
        };
        document.head.appendChild(script);
      }
    } catch (error) {
      this.logger.warn('Socket.IO connection setup failed, trying WebSocket', {
        error: error.message
      });
      this.tryWebSocketConnection(sessionId);
    }
  }
 
  /**
   * Reconnect Socket.IO if connection is lost
   * @param {string} sessionId - Session ID for tracking
   */
  reconnectSocketIO(sessionId) {
    if (this.isReconnecting) return;
    this.isReconnecting = true;
    this.logger.info('Attempting to reconnect Socket.IO', {
      sessionId
    });
    console.log('🔄 [PROGRESS] Attempting to reconnect Socket.IO');
 
    // Close existing connections
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
 
    // Try to reconnect
    setTimeout(() => {
      this.trySocketIOConnection(sessionId);
      this.isReconnecting = false;
    }, 1000);
  }
 
  /**
   * Connect with Socket.IO
   * @param {Function} io - Socket.IO client function
   * @param {string} sessionId - Session ID for tracking
   */
  connectWithSocketIO(io, sessionId) {
    try {
      // Create Socket.IO connection
      this.socket = io('/', {
        transports: ['websocket', 'polling'],
        timeout: 5000,
        forceNew: true
      });
      this.socket.on('connect', () => {
        this.connectionType = 'socketio';
        this.updateConnectionType('Socket.IO');
        this.logger.info('Socket.IO connected', {
          sessionId,
          socketId: this.socket.id
        });
        console.log(`🔌 [PROGRESS] Socket.IO connected (ID: ${this.socket.id})`);
 
        // Join session room
        this.socket.emit('registerSession', sessionId);
 
        // Also try the join-session event for compatibility
        this.socket.emit('join-session', {
          sessionId
        });
      });
      this.socket.on('progress', data => {
        console.log('🔄 [PROGRESS] Received progress event:', data);
        this.handleProgressEvent(data);
      });
      this.socket.on('completion', data => {
        console.log('✅ [PROGRESS] Received completion event:', data);
        this.handleCompletionEvent(data);
      });
 
      // Also listen for 'complete' for compatibility
      this.socket.on('complete', data => {
        console.log('✅ [PROGRESS] Received complete event:', data);
        this.handleCompletionEvent(data);
      });
      this.socket.on('error', data => {
        console.log('❌ [PROGRESS] Received error event:', data);
        this.handleErrorEvent(data);
      });
      this.socket.on('disconnect', () => {
        console.log('🔌 [PROGRESS] Socket.IO disconnected');
        this.logger.warn('Socket.IO disconnected');
        this.handleConnectionFailure();
      });
      this.socket.on('connect_error', error => {
        console.log('❌ [PROGRESS] Socket.IO connection error:', error.message);
        this.logger.warn('Socket.IO connection error', {
          error: error.message
        });
        this.handleConnectionFailure();
      });
    } catch (error) {
      this.logger.warn('Socket.IO connection failed, trying WebSocket', {
        error: error.message
      });
      this.tryWebSocketConnection(sessionId);
    }
  }
 
  /**
   * Try WebSocket connection as fallback
   * @param {string} sessionId - Session ID for tracking
   */
  tryWebSocketConnection(sessionId) {
    try {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const wsUrl = `${protocol}//${window.location.host}/ws`;
      this.websocket = new WebSocket(wsUrl);
      this.websocket.onopen = () => {
        this.connectionType = 'websocket';
        this.updateConnectionType('WebSocket');
        this.logger.info('WebSocket connected', {
          sessionId
        });
 
        // Send session join message
        this.websocket.send(JSON.stringify({
          type: 'join-session',
          sessionId: sessionId
        }));
      };
      this.websocket.onmessage = event => {
        try {
          const data = JSON.parse(event.data);
          switch (data.type) {
            case 'progress':
              this.handleProgressEvent(data);
              break;
            case 'complete':
              this.handleCompletionEvent(data);
              break;
            case 'error':
              this.handleErrorEvent(data);
              break;
          }
        } catch (error) {
          this.logger.error('Error parsing WebSocket message', {
            error: error.message
          });
        }
      };
      this.websocket.onclose = event => {
        this.logger.warn('WebSocket closed', {
          code: event.code,
          reason: event.reason
        });
        this.handleConnectionFailure();
      };
      this.websocket.onerror = error => {
        this.logger.error('WebSocket error', {
          error: error.message
        });
        this.handleConnectionFailure();
      };
    } catch (error) {
      this.logger.error('WebSocket connection failed', {
        error: error.message
      });
      this.handleConnectionFailure();
    }
  }
 
  /**
   * Handle connection failure and implement fallback strategy
   */
  handleConnectionFailure() {
    this.connectionRetries++;
    if (this.connectionRetries <= this.maxRetries) {
      this.logger.info('Retrying connection', {
        attempt: this.connectionRetries,
        maxRetries: this.maxRetries
      });
      setTimeout(() => {
        if (this.currentSessionId) {
          this.initializeRealTimeConnection(this.currentSessionId);
        }
      }, 1000 * this.connectionRetries); // Exponential backoff
    } else {
      this.logger.warn('Max connection retries reached, falling back to polling');
      this.updateConnectionType('Polling (Fallback)');
    }
  }
 
  /**
   * Close all real-time connections
   */
  closeConnections() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
    if (this.websocket) {
      this.websocket.close(1000, 'Operation completed');
      this.websocket = null;
    }
    this.connectionType = null;
    this.logger.debug('Real-time connections closed');
  }
 
  /**
   * Update session ID for tracking
   * @param {string} sessionId - New session ID
   */
  updateSessionId(sessionId) {
    if (!sessionId) {
      this.logger.warn('No session ID provided for update');
      return;
    }
    this.currentSessionId = sessionId;
 
    // Update session ID display
    const sessionElement = this.progressContainer.querySelector('.detail-value.session-id');
    if (sessionElement) {
      sessionElement.textContent = sessionId;
    }
    this.logger.info('Session ID updated', {
      sessionId
    });
  }
 
  /**
   * Handle progress event from real-time connection
   * @param {Object} data - Progress event data
   */
  handleProgressEvent(data) {
    if (!data) {
      this.logger.warn('No progress data received');
      return;
    }
    const {
      current,
      total,
      message,
      counts
    } = data;
    this.updateProgress(current, total, message, counts);
    this.logger.debug('Progress event handled', {
      current,
      total,
      message
    });
  }
 
  /**
   * Handle completion event from real-time connection
   * @param {Object} data - Completion event data
   */
  handleCompletionEvent(data) {
    this.completeOperation(data);
    this.logger.info('Completion event handled', {
      data
    });
  }
 
  /**
   * Handle error event from real-time connection
   * @param {Object} data - Error event data
   */
  handleErrorEvent(data) {
    const {
      message,
      details
    } = data;
    this.handleOperationError(message, details);
    this.logger.error('Error event handled', {
      message,
      details
    });
  }
 
  /**
   * Update progress display with current values
   * @param {number} current - Current progress value
   * @param {number} total - Total progress value
   * @param {string} message - Progress message
   * @param {Object} details - Additional progress details
   */
  updateProgress(current, total) {
    let message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
    let details = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    if (!this.isEnabled || !this.progressContainer) {
      this.logger.warn('Progress manager not enabled or container not found');
      return;
    }
 
    // Update progress bar
    const progressBar = this.progressContainer.querySelector('.progress-bar-fill');
    if (progressBar) {
      const percentage = total > 0 ? Math.min(100, Math.round(current / total * 100)) : 0;
      progressBar.style.width = `${percentage}%`;
    }
 
    // Update percentage text
    const percentageElement = this.progressContainer.querySelector('.progress-percentage');
    if (percentageElement) {
      const percentage = total > 0 ? Math.min(100, Math.round(current / total * 100)) : 0;
      percentageElement.textContent = `${percentage}%`;
    }
 
    // Update progress text
    const progressText = this.progressContainer.querySelector('.progress-text');
    if (progressText && message) {
      progressText.textContent = message;
    }
 
    // Update step indicator based on progress
    if (total > 0) {
      const percentage = current / total * 100;
      this.updateStepIndicatorBasedOnProgress(percentage);
    }
 
    // Update statistics if provided
    if (details && typeof details === 'object') {
      this.stats = {
        ...this.stats,
        ...details
      };
      this.updateStatsDisplay();
    }
    this.logger.debug('Progress updated', {
      current,
      total,
      message,
      details
    });
  }
 
  /**
   * Update statistics display in the UI
   */
  updateStatsDisplay() {
    if (!this.progressContainer) return;
    Object.entries(this.stats).forEach(_ref => {
      let [key, value] = _ref;
      const statElement = this.progressContainer.querySelector(`.stat-value.${key}`);
      if (statElement) {
        statElement.textContent = value || 0;
      }
    });
    this.logger.debug('Statistics display updated', {
      stats: this.stats
    });
  }
 
  /**
   * Update step indicator based on progress percentage
   * @param {number} percentage - Progress percentage (0-100)
   */
  updateStepIndicatorBasedOnProgress(percentage) {
    let step = 'init';
    if (percentage >= 100) {
      step = 'complete';
    } else if (percentage >= 75) {
      step = 'process';
    } else if (percentage >= 25) {
      step = 'validate';
    }
    this.updateStepIndicator(step);
  }
 
  /**
   * Update step indicator to show current operation phase
   * @param {string} step - Step name (init, validate, process, complete)
   */
  updateStepIndicator(step) {
    if (!this.progressContainer) return;
    const steps = this.progressContainer.querySelectorAll('.step');
    steps.forEach(stepElement => {
      stepElement.classList.remove('active', 'completed');
    });
    const currentStep = this.progressContainer.querySelector(`[data-step="${step}"]`);
    if (currentStep) {
      currentStep.classList.add('active');
    }
 
    // Mark previous steps as completed
    const stepOrder = this.getStepOrder(step);
    steps.forEach(stepElement => {
      const stepName = stepElement.getAttribute('data-step');
      const stepIndex = this.getStepOrder(stepName);
      if (stepIndex < stepOrder) {
        stepElement.classList.add('completed');
      }
    });
    this.logger.debug('Step indicator updated', {
      step
    });
  }
 
  /**
   * Get step order for comparison
   * @param {string} step - Step name
   * @returns {number} Step order (0-3)
   */
  getStepOrder(step) {
    const order = {
      init: 0,
      validate: 1,
      process: 2,
      complete: 3
    };
    return order[step] || 0;
  }
 
  /**
   * Start timing updates for operation duration
   */
  startTimingUpdates() {
    if (this.timingInterval) {
      clearInterval(this.timingInterval);
    }
    this.timingInterval = setInterval(() => {
      this.updateTiming();
    }, 1000);
    this.logger.debug('Timing updates started');
  }
 
  /**
   * Update timing display with elapsed time and ETA
   */
  updateTiming() {
    if (!this.startTime || !this.progressContainer) return;
    const elapsed = Date.now() - this.startTime;
    const elapsedElement = this.progressContainer.querySelector('.elapsed-value');
    if (elapsedElement) {
      elapsedElement.textContent = this.formatDuration(elapsed);
    }
 
    // Calculate ETA if we have progress data
    if (this.stats.total > 0 && this.stats.processed > 0) {
      const progress = this.stats.processed / this.stats.total;
      if (progress > 0) {
        const estimatedTotal = elapsed / progress;
        const remaining = estimatedTotal - elapsed;
        const etaElement = this.progressContainer.querySelector('.eta-value');
        if (etaElement) {
          etaElement.textContent = this.formatDuration(remaining);
        }
      }
    }
    this.logger.debug('Timing updated', {
      elapsed
    });
  }
 
  /**
   * Complete operation with results
   * @param {Object} results - Operation results
   * @param {number} results.processed - Number of processed items
   * @param {number} results.success - Number of successful items
   * @param {number} results.failed - Number of failed items
   * @param {number} results.skipped - Number of skipped items
   */
  completeOperation() {
    let results = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    if (!this.isEnabled) {
      this.logger.warn('Progress manager not enabled - cannot complete operation');
      return;
    }
 
    // Stop timing updates
    if (this.timingInterval) {
      clearInterval(this.timingInterval);
      this.timingInterval = null;
    }
 
    // Close real-time connections
    this.closeConnections();
 
    // Update final progress
    const {
      processed,
      success,
      failed,
      skipped
    } = results;
    this.updateProgress(processed || 0, processed || 0, 'Operation completed');
 
    // Update final statistics
    this.stats = {
      ...this.stats,
      ...results
    };
    this.updateStatsDisplay();
 
    // Mark as complete
    this.updateStepIndicator('complete');
 
    // Call completion callback if provided
    if (this.completeCallback && typeof this.completeCallback === 'function') {
      this.completeCallback(results);
    }
    this.isActive = false;
    this.logger.info('Operation completed', {
      results
    });
  }
 
  /**
   * Handle operation error
   * @param {string} message - Error message
   * @param {Object} details - Error details
   */
  handleOperationError(message) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    if (!this.isEnabled) {
      this.logger.warn('Progress manager not enabled - cannot handle error');
      return;
    }
 
    // Stop timing updates
    if (this.timingInterval) {
      clearInterval(this.timingInterval);
      this.timingInterval = null;
    }
 
    // Close real-time connections
    this.closeConnections();
 
    // Update progress text with error
    const progressText = this.progressContainer.querySelector('.progress-text');
    if (progressText) {
      progressText.textContent = `Error: ${message}`;
      progressText.classList.add('error');
    }
    this.isActive = false;
    this.logger.error('Operation error', {
      message,
      details
    });
  }
 
  /**
   * Cancel current operation
   */
  cancelOperation() {
    if (!this.isEnabled || !this.isActive) {
      this.logger.warn('No active operation to cancel');
      return;
    }
 
    // Stop timing updates
    if (this.timingInterval) {
      clearInterval(this.timingInterval);
      this.timingInterval = null;
    }
 
    // Close real-time connections
    this.closeConnections();
 
    // Call cancel callback if provided
    if (this.cancelCallback && typeof this.cancelCallback === 'function') {
      this.cancelCallback();
    }
    this.isActive = false;
    this.hideProgress();
    this.logger.info('Operation cancelled');
  }
 
  /**
   * Show progress display
   */
  showProgress() {
    if (!this.isEnabled || !this.progressContainer) {
      this.logger.warn('Progress manager not enabled or container not found');
      return;
    }
 
    // Make sure the container is visible
    this.progressContainer.style.display = 'block';
    this.progressContainer.classList.add('visible');
 
    // Force visibility with !important to override any CSS that might hide it
    this.progressContainer.setAttribute('style', 'display: block !important; visibility: visible !important;');
 
    // Focus management for accessibility
    const cancelButton = this.progressContainer.querySelector('.cancel-operation');
    if (cancelButton) {
      cancelButton.focus();
    }
    this.logger.debug('Progress display shown', {
      containerId: this.progressContainer.id
    });
 
    // Log to console for debugging
    console.log(`🔍 [PROGRESS] Showing progress container: ${this.progressContainer.id}`);
  }
 
  /**
   * Hide progress display
   */
  hideProgress() {
    if (!this.progressContainer) return;
 
    // Log before hiding
    this.logger.debug('Hiding progress display', {
      containerId: this.progressContainer.id
    });
    console.log(`🔍 [PROGRESS] Hiding progress container: ${this.progressContainer.id}`);
    this.progressContainer.classList.remove('visible');
 
    // Immediately hide the container
    this.progressContainer.style.display = 'none';
    this.logger.debug('Progress display hidden');
  }
 
  /**
   * Update operation title
   * @param {string} operationType - Type of operation
   */
  updateOperationTitle(operationType) {
    if (!this.progressContainer) return;
    const titleElement = this.progressContainer.querySelector('.title-text');
    if (titleElement) {
      const titles = {
        import: 'Import Users',
        export: 'Export Users',
        delete: 'Delete Users',
        modify: 'Modify Users'
      };
      titleElement.textContent = titles[operationType] || 'Operation in Progress';
    }
    this.logger.debug('Operation title updated', {
      operationType
    });
  }
 
  /**
   * Update operation details
   * @param {Object} options - Operation options
   * @param {string} options.populationName - Population name
   * @param {string} options.populationId - Population ID
   * @param {number} options.totalUsers - Total number of users
   */
  updateOperationDetails() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    if (!this.progressContainer) return;
    const {
      populationName,
      populationId,
      totalUsers
    } = options;
 
    // Update operation type
    const operationTypeElement = this.progressContainer.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = this.currentOperation || 'Unknown';
    }
 
    // Update population info
    const populationElement = this.progressContainer.querySelector('.detail-value.population-info');
    if (populationElement) {
      populationElement.textContent = populationName || populationId || 'Unknown';
    }
 
    // Update total users in stats
    if (totalUsers) {
      this.stats.total = totalUsers;
      this.updateStatsDisplay();
    }
    this.logger.debug('Operation details updated', {
      options
    });
  }
 
  /**
   * Update operation status
   * @param {string} status - Operation status
   * @param {string} message - Status message
   */
  updateOperationStatus(status) {
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    if (!this.progressContainer) return;
    const subtitleElement = this.progressContainer.querySelector('.operation-subtitle');
    if (subtitleElement) {
      subtitleElement.textContent = message || status;
    }
    this.logger.debug('Operation status updated', {
      status,
      message
    });
  }
 
  /**
   * Update connection type display
   * @param {string} type - Connection type
   */
  updateConnectionType(type) {
    if (!this.progressContainer) return;
    const connectionElement = this.progressContainer.querySelector('.detail-value.connection-type');
    if (connectionElement) {
      connectionElement.textContent = type;
    }
    this.logger.debug('Connection type updated', {
      type
    });
  }
 
  /**
   * Reset operation statistics
   */
  resetOperationStats() {
    this.stats = {
      processed: 0,
      success: 0,
      failed: 0,
      skipped: 0,
      total: 0
    };
    this.updateStatsDisplay();
    this.logger.debug('Operation statistics reset');
  }
 
  /**
   * Format duration in milliseconds to human readable string
   * @param {number} milliseconds - Duration in milliseconds
   * @returns {string} Formatted duration string
   */
  formatDuration(milliseconds) {
    const seconds = Math.floor(milliseconds / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    if (hours > 0) {
      return `${hours}:${String(minutes % 60).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
    } else if (minutes > 0) {
      return `${minutes}:${String(seconds % 60).padStart(2, '0')}`;
    } else {
      return `${seconds}s`;
    }
  }
 
  /**
   * Set progress callback function
   * @param {Function} callback - Progress callback function
   */
  setProgressCallback(callback) {
    this.progressCallback = callback;
    this.logger.debug('Progress callback set');
  }
 
  /**
   * Set completion callback function
   * @param {Function} callback - Completion callback function
   */
  setCompleteCallback(callback) {
    this.completeCallback = callback;
    this.logger.debug('Completion callback set');
  }
 
  /**
   * Set cancel callback function
   * @param {Function} callback - Cancel callback function
   */
  setCancelCallback(callback) {
    this.cancelCallback = callback;
    this.logger.debug('Cancel callback set');
  }
 
  /**
   * Debug logging for development
   * @param {string} area - Debug area
   * @param {string} message - Debug message
   */
  debugLog(area, message) {
    if (DEBUG_MODE) {
      this.logger.debug(`[${area}] ${message}`);
    }
  }
 
  /**
   * Clean up resources and destroy the progress manager
   */
  destroy() {
    // Stop timing updates
    if (this.timingInterval) {
      clearInterval(this.timingInterval);
      this.timingInterval = null;
    }
 
    // Close connections
    this.closeConnections();
 
    // Clear callbacks
    this.progressCallback = null;
    this.completeCallback = null;
    this.cancelCallback = null;
 
    // Reset state
    this.isActive = false;
    this.currentOperation = null;
    this.currentSessionId = null;
    this.logger.info('Progress manager destroyed');
  }
}
 
// Create and export default instance
exports.ProgressManager = ProgressManager;
const progressManager = new ProgressManager();
 
// Export the class and instance
var _default = exports.default = progressManager;
 
}).call(this)}).call(this,require('_process'))
},{"./element-registry.js":47,"./message-formatter.js":56,"./session-manager.js":61,"./winston-logger.js":70,"@babel/runtime/helpers/interopRequireDefault":2,"_process":29}],60:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.ProgressSubsystem = void 0;
/**
 * Progress Management Subsystem
 * Modern replacement for legacy ProgressManager
 * Handles all progress tracking, UI updates, and real-time communication
 */
 
class ProgressSubsystem {
  constructor(logger, uiManager, eventBus, realtimeComm) {
    this.logger = logger;
    this.uiManager = uiManager;
    this.eventBus = eventBus;
    this.realtimeComm = realtimeComm;
 
    // Progress state
    this.currentOperation = null;
    this.isActive = false;
    this.stats = {
      processed: 0,
      successful: 0,
      failed: 0,
      total: 0,
      errors: []
    };
 
    // UI elements
    this.progressContainer = null;
    this.progressBar = null;
    this.statusText = null;
    this.detailsContainer = null;
 
    // Event listeners
    this.setupEventListeners();
    this.logger.info('Progress Subsystem initialized');
  }
 
  /**
   * Initialize the progress subsystem
   */
  async init() {
    try {
      this.initializeProgressElements();
      this.setupRealtimeListeners();
      this.logger.info('Progress Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Progress Subsystem', error);
      throw error;
    }
  }
 
  /**
   * Initialize progress UI elements
   */
  initializeProgressElements() {
    this.progressContainer = document.getElementById('progress-container');
    this.progressBar = document.querySelector('.progress-bar');
    this.statusText = document.querySelector('.progress-status');
    this.detailsContainer = document.querySelector('.progress-details');
    if (!this.progressContainer) {
      this.logger.warn('Progress container not found, creating dynamic elements');
      this.createProgressElements();
    }
  }
 
  /**
   * Create progress elements dynamically
   */
  createProgressElements() {
    // Create progress container if it doesn't exist
    const container = document.createElement('div');
    container.id = 'progress-container';
    container.className = 'progress-container';
    container.style.display = 'none';
    container.innerHTML = `
            <div class="progress-header">
                <h3 class="progress-title">Operation Progress</h3>
                <button class="progress-close" aria-label="Close progress">×</button>
            </div>
            <div class="progress-content">
                <div class="progress-bar-container">
                    <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                        <div class="progress-fill"></div>
                    </div>
                    <div class="progress-percentage">0%</div>
                </div>
                <div class="progress-status">Ready</div>
                <div class="progress-details">
                    <div class="progress-stats">
                        <span class="stat-item">Processed: <span class="stat-processed">0</span></span>
                        <span class="stat-item">Successful: <span class="stat-successful">0</span></span>
                        <span class="stat-item">Failed: <span class="stat-failed">0</span></span>
                        <span class="stat-item">Total: <span class="stat-total">0</span></span>
                    </div>
                    <div class="progress-errors" style="display: none;">
                        <h4>Errors:</h4>
                        <ul class="error-list"></ul>
                    </div>
                </div>
            </div>
        `;
    document.body.appendChild(container);
    this.progressContainer = container;
    this.progressBar = container.querySelector('.progress-bar');
    this.statusText = container.querySelector('.progress-status');
    this.detailsContainer = container.querySelector('.progress-details');
 
    // Setup close button
    const closeBtn = container.querySelector('.progress-close');
    closeBtn?.addEventListener('click', () => this.hide());
  }
 
  /**
   * Setup event listeners
   */
  setupEventListeners() {
    this.eventBus.on('operation:started', data => {
      this.startOperation(data.type, data.options);
    });
    this.eventBus.on('operation:progress', data => {
      this.updateProgress(data);
    });
    this.eventBus.on('operation:completed', data => {
      this.completeOperation(data);
    });
    this.eventBus.on('operation:error', data => {
      this.handleError(data);
    });
  }
 
  /**
   * Setup real-time listeners
   */
  setupRealtimeListeners() {
    if (this.realtimeComm) {
      this.realtimeComm.on('progress', data => {
        this.updateProgress(data);
      });
      this.realtimeComm.on('operation-complete', data => {
        this.completeOperation(data);
      });
      this.realtimeComm.on('operation-error', data => {
        this.handleError(data);
      });
    }
  }
 
  /**
   * Start a new operation
   */
  startOperation(operationType) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.currentOperation = operationType;
    this.isActive = true;
    this.stats = {
      processed: 0,
      successful: 0,
      failed: 0,
      total: options.total || 0,
      errors: []
    };
    this.show();
    this.updateOperationDetails(options);
    this.updateStatus(`Starting ${operationType} operation...`);
    this.updateProgressBar(0);
    this.logger.info('Operation started', {
      type: operationType,
      options
    });
    this.eventBus.emit('progress:operation-started', {
      type: operationType,
      options
    });
  }
 
  /**
   * Update progress
   */
  updateProgress(data) {
    if (!this.isActive) return;
 
    // Update stats
    if (data.processed !== undefined) this.stats.processed = data.processed;
    if (data.successful !== undefined) this.stats.successful = data.successful;
    if (data.failed !== undefined) this.stats.failed = data.failed;
    if (data.total !== undefined) this.stats.total = data.total;
    if (data.error) this.stats.errors.push(data.error);
 
    // Update UI
    this.updateProgressBar();
    this.updateStatsDisplay();
    if (data.message) {
      this.updateStatus(data.message);
    }
    this.logger.debug('Progress updated', {
      stats: this.stats,
      message: data.message
    });
    this.eventBus.emit('progress:updated', {
      stats: this.stats,
      data
    });
  }
 
  /**
   * Update progress bar
   */
  updateProgressBar() {
    let percentage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    if (!this.progressBar) return;
    let percent = percentage;
    if (percent === null && this.stats.total > 0) {
      percent = Math.round(this.stats.processed / this.stats.total * 100);
    }
    if (percent !== null) {
      const fill = this.progressBar.querySelector('.progress-fill');
      const percentageText = this.progressContainer?.querySelector('.progress-percentage');
      if (fill) {
        fill.style.width = `${percent}%`;
      }
      if (percentageText) {
        percentageText.textContent = `${percent}%`;
      }
      this.progressBar.setAttribute('aria-valuenow', percent.toString());
    }
  }
 
  /**
   * Update stats display
   */
  updateStatsDisplay() {
    if (!this.detailsContainer) return;
    const elements = {
      processed: this.detailsContainer.querySelector('.stat-processed'),
      successful: this.detailsContainer.querySelector('.stat-successful'),
      failed: this.detailsContainer.querySelector('.stat-failed'),
      total: this.detailsContainer.querySelector('.stat-total')
    };
    Object.keys(elements).forEach(key => {
      if (elements[key]) {
        elements[key].textContent = this.stats[key].toString();
      }
    });
 
    // Update errors display
    if (this.stats.errors.length > 0) {
      this.updateErrorsDisplay();
    }
  }
 
  /**
   * Update errors display
   */
  updateErrorsDisplay() {
    const errorsContainer = this.detailsContainer?.querySelector('.progress-errors');
    const errorsList = this.detailsContainer?.querySelector('.error-list');
    if (errorsContainer && errorsList) {
      errorsContainer.style.display = 'block';
      errorsList.innerHTML = '';
      this.stats.errors.slice(-5).forEach(error => {
        // Show last 5 errors
        const li = document.createElement('li');
        li.textContent = error.message || error.toString();
        li.className = 'error-item';
        errorsList.appendChild(li);
      });
    }
  }
 
  /**
   * Update operation details
   */
  updateOperationDetails(options) {
    const title = this.progressContainer?.querySelector('.progress-title');
    if (title) {
      title.textContent = `${this.currentOperation} Operation Progress`;
    }
 
    // Update any operation-specific details
    if (options.populationName) {
      this.updateStatus(`Processing population: ${options.populationName}`);
    }
  }
 
  /**
   * Update status text
   */
  updateStatus(message) {
    if (this.statusText) {
      this.statusText.textContent = message;
    }
    this.logger.debug('Status updated', {
      message
    });
  }
 
  /**
   * Complete operation
   */
  completeOperation(data) {
    this.isActive = false;
    const success = this.stats.failed === 0;
    const message = success ? `${this.currentOperation} completed successfully! Processed ${this.stats.processed} items.` : `${this.currentOperation} completed with ${this.stats.failed} errors. Processed ${this.stats.processed} items.`;
    this.updateStatus(message);
    this.updateProgressBar(100);
 
    // Auto-hide after delay for successful operations
    if (success) {
      setTimeout(() => this.hide(), 3000);
    }
    this.logger.info('Operation completed', {
      type: this.currentOperation,
      stats: this.stats,
      success
    });
    this.eventBus.emit('progress:operation-completed', {
      type: this.currentOperation,
      stats: this.stats,
      success,
      data
    });
  }
 
  /**
   * Handle operation error
   */
  handleError(error) {
    this.stats.errors.push(error);
    this.stats.failed++;
    this.updateStatsDisplay();
    this.updateStatus(`Error: ${error.message || error.toString()}`);
    this.logger.error('Operation error', error);
    this.eventBus.emit('progress:error', {
      error,
      stats: this.stats
    });
  }
 
  /**
   * Show progress container
   */
  show() {
    if (this.progressContainer) {
      this.progressContainer.style.display = 'block';
      this.progressContainer.classList.add('active');
    }
    this.eventBus.emit('progress:shown');
  }
 
  /**
   * Hide progress container
   */
  hide() {
    if (this.progressContainer) {
      this.progressContainer.style.display = 'none';
      this.progressContainer.classList.remove('active');
    }
    this.isActive = false;
    this.eventBus.emit('progress:hidden');
  }
 
  /**
   * Reset progress state
   */
  reset() {
    this.currentOperation = null;
    this.isActive = false;
    this.stats = {
      processed: 0,
      successful: 0,
      failed: 0,
      total: 0,
      errors: []
    };
    this.updateProgressBar(0);
    this.updateStatsDisplay();
    this.updateStatus('Ready');
    this.logger.info('Progress subsystem reset');
    this.eventBus.emit('progress:reset');
  }
 
  /**
   * Get current progress state
   */
  getState() {
    return {
      currentOperation: this.currentOperation,
      isActive: this.isActive,
      stats: {
        ...this.stats
      }
    };
  }
 
  /**
   * Destroy the progress subsystem
   */
  destroy() {
    this.hide();
    this.isActive = false;
    if (this.progressContainer && this.progressContainer.parentNode) {
      this.progressContainer.parentNode.removeChild(this.progressContainer);
    }
    this.logger.info('Progress Subsystem destroyed');
    this.eventBus.emit('progress:destroyed');
  }
}
 
// Export for ES modules
exports.ProgressSubsystem = ProgressSubsystem;
var _default = exports.default = ProgressSubsystem;
 
},{}],61:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.sessionManager = exports.default = void 0;
var _winstonLogger = require("./winston-logger.js");
/**
 * Session Manager for PingOne Import Tool
 * 
 * Handles session ID generation, validation, and management for SSE connections
 * across all operations (import, export, modify, delete).
 * 
 * Features:
 * - Centralized session ID generation
 * - Session ID validation and format checking
 * - Session tracking and cleanup
 * - Error handling for missing/invalid session IDs
 */
 
/**
 * Session Manager Class
 */
class SessionManager {
  constructor() {
    this.logger = (0, _winstonLogger.createWinstonLogger)({
      service: 'pingone-import-session',
      environment: process.env.NODE_ENV || 'development'
    });
    this.activeSessions = new Map();
    this.sessionCounter = 0;
  }
 
  /**
   * Generate a unique session ID
   * @returns {string} Unique session identifier
   */
  generateSessionId() {
    try {
      const timestamp = Date.now();
      const random = Math.random().toString(36).substring(2, 15);
      const counter = ++this.sessionCounter;
      const sessionId = `session_${timestamp}_${random}_${counter}`;
      this.logger.debug('Session ID generated', {
        sessionId
      });
      return sessionId;
    } catch (error) {
      this.logger.error('Error generating session ID', {
        error: error.message
      });
      // Fallback to simple timestamp-based ID
      return `session_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
    }
  }
 
  /**
   * Validate session ID format and structure
   * @param {string} sessionId - Session ID to validate
   * @returns {boolean} True if valid, false otherwise
   */
  validateSessionId(sessionId) {
    try {
      if (!sessionId || typeof sessionId !== 'string') {
        this.logger.warn('Session ID validation failed: null/undefined/non-string', {
          sessionId,
          type: typeof sessionId
        });
        return false;
      }
      if (sessionId.trim() === '') {
        this.logger.warn('Session ID validation failed: empty string');
        return false;
      }
 
      // Check for minimum length (should be at least 8 characters)
      if (sessionId.length < 8) {
        this.logger.warn('Session ID validation failed: too short', {
          length: sessionId.length
        });
        return false;
      }
 
      // Check for valid characters (alphanumeric, underscore, hyphen)
      const validPattern = /^[a-zA-Z0-9_-]+$/;
      if (!validPattern.test(sessionId)) {
        this.logger.warn('Session ID validation failed: invalid characters', {
          sessionId
        });
        return false;
      }
      this.logger.debug('Session ID validation passed', {
        sessionId
      });
      return true;
    } catch (error) {
      this.logger.error('Error validating session ID', {
        error: error.message,
        sessionId
      });
      return false;
    }
  }
 
  /**
   * Register an active session
   * @param {string} sessionId - Session ID to register
   * @param {string} operationType - Type of operation (import, export, etc.)
   * @param {Object} metadata - Additional session metadata
   */
  registerSession(sessionId, operationType) {
    let metadata = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    try {
      if (!this.validateSessionId(sessionId)) {
        this.logger.error('Cannot register invalid session ID', {
          sessionId,
          operationType
        });
        return false;
      }
      const sessionData = {
        sessionId,
        operationType,
        createdAt: Date.now(),
        lastActivity: Date.now(),
        metadata
      };
      this.activeSessions.set(sessionId, sessionData);
      this.logger.info('Session registered', {
        sessionId,
        operationType,
        metadata
      });
      return true;
    } catch (error) {
      this.logger.error('Error registering session', {
        error: error.message,
        sessionId,
        operationType
      });
      return false;
    }
  }
 
  /**
   * Update session activity timestamp
   * @param {string} sessionId - Session ID to update
   */
  updateSessionActivity(sessionId) {
    try {
      const session = this.activeSessions.get(sessionId);
      if (session) {
        session.lastActivity = Date.now();
        this.logger.debug('Session activity updated', {
          sessionId
        });
      } else {
        this.logger.warn('Session not found for activity update', {
          sessionId
        });
      }
    } catch (error) {
      this.logger.error('Error updating session activity', {
        error: error.message,
        sessionId
      });
    }
  }
 
  /**
   * Unregister a session
   * @param {string} sessionId - Session ID to unregister
   */
  unregisterSession(sessionId) {
    try {
      const session = this.activeSessions.get(sessionId);
      if (session) {
        this.activeSessions.delete(sessionId);
        this.logger.info('Session unregistered', {
          sessionId,
          operationType: session.operationType
        });
      } else {
        this.logger.warn('Session not found for unregistration', {
          sessionId
        });
      }
    } catch (error) {
      this.logger.error('Error unregistering session', {
        error: error.message,
        sessionId
      });
    }
  }
 
  /**
   * Get session information
   * @param {string} sessionId - Session ID to retrieve
   * @returns {Object|null} Session data or null if not found
   */
  getSession(sessionId) {
    try {
      return this.activeSessions.get(sessionId) || null;
    } catch (error) {
      this.logger.error('Error getting session', {
        error: error.message,
        sessionId
      });
      return null;
    }
  }
 
  /**
   * Get all active sessions
   * @returns {Array} Array of active session data
   */
  getActiveSessions() {
    try {
      return Array.from(this.activeSessions.values());
    } catch (error) {
      this.logger.error('Error getting active sessions', {
        error: error.message
      });
      return [];
    }
  }
 
  /**
   * Clean up expired sessions
   * @param {number} maxAge - Maximum age in milliseconds (default: 1 hour)
   */
  cleanupExpiredSessions() {
    let maxAge = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 60 * 60 * 1000;
    try {
      const now = Date.now();
      const expiredSessions = [];
      for (const [sessionId, session] of this.activeSessions.entries()) {
        if (now - session.lastActivity > maxAge) {
          expiredSessions.push(sessionId);
        }
      }
      expiredSessions.forEach(sessionId => {
        this.unregisterSession(sessionId);
      });
      if (expiredSessions.length > 0) {
        this.logger.info('Cleaned up expired sessions', {
          count: expiredSessions.length
        });
      }
    } catch (error) {
      this.logger.error('Error cleaning up expired sessions', {
        error: error.message
      });
    }
  }
 
  /**
   * Get session statistics
   * @returns {Object} Session statistics
   */
  getSessionStats() {
    try {
      const sessions = this.getActiveSessions();
      const stats = {
        total: sessions.length,
        byOperation: {},
        oldest: null,
        newest: null
      };
      sessions.forEach(session => {
        // Count by operation type
        stats.byOperation[session.operationType] = (stats.byOperation[session.operationType] || 0) + 1;
 
        // Track oldest and newest
        if (!stats.oldest || session.createdAt < stats.oldest.createdAt) {
          stats.oldest = session;
        }
        if (!stats.newest || session.createdAt > stats.newest.createdAt) {
          stats.newest = session;
        }
      });
      return stats;
    } catch (error) {
      this.logger.error('Error getting session stats', {
        error: error.message
      });
      return {
        total: 0,
        byOperation: {},
        oldest: null,
        newest: null
      };
    }
  }
}
 
// Export singleton instance
const sessionManager = exports.sessionManager = new SessionManager();
var _default = exports.default = sessionManager;
 
}).call(this)}).call(this,require('_process'))
},{"./winston-logger.js":70,"_process":29}],62:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.SessionSubsystem = void 0;
/**
 * Session Management Subsystem
 * Modern replacement for legacy SessionManager
 * Handles session lifecycle, activity tracking, and cleanup
 */
 
class SessionSubsystem {
  constructor(logger, settingsSubsystem, eventBus) {
    this.logger = logger;
    this.settingsSubsystem = settingsSubsystem;
    this.eventBus = eventBus;
 
    // Session state
    this.currentSession = null;
    this.activeSessions = new Map();
    this.sessionTimeout = 30 * 60 * 1000; // 30 minutes default
    this.cleanupInterval = null;
    this.activityTimer = null;
 
    // Session configuration
    this.config = {
      maxSessions: 10,
      sessionTimeout: 30 * 60 * 1000,
      activityCheckInterval: 60 * 1000,
      // 1 minute
      autoCleanup: true
    };
    this.setupEventListeners();
    this.logger.info('Session Subsystem initialized');
  }
 
  /**
   * Initialize the session subsystem
   */
  async init() {
    try {
      await this.loadConfiguration();
      this.startActivityMonitoring();
      this.startCleanupProcess();
 
      // Create initial session
      await this.createSession();
      this.logger.info('Session Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Session Subsystem', error);
      throw error;
    }
  }
 
  /**
   * Load session configuration
   */
  async loadConfiguration() {
    try {
      await this.settingsSubsystem.loadCurrentSettings();
      const settings = this.settingsSubsystem.currentSettings;
      if (settings.session) {
        this.config = {
          ...this.config,
          ...settings.session
        };
        this.sessionTimeout = this.config.sessionTimeout;
      }
    } catch (error) {
      this.logger.warn('Failed to load session configuration, using defaults', error);
    }
  }
 
  /**
   * Setup event listeners
   */
  setupEventListeners() {
    // Listen for user activity events
    this.eventBus.on('user:activity', () => {
      this.updateActivity();
    });
 
    // Listen for authentication events
    this.eventBus.on('auth:login', data => {
      this.handleLogin(data);
    });
    this.eventBus.on('auth:logout', () => {
      this.handleLogout();
    });
 
    // Listen for settings changes
    this.eventBus.on('settings:updated', data => {
      if (data.session) {
        this.updateConfiguration(data.session);
      }
    });
 
    // Browser events
    window.addEventListener('beforeunload', () => {
      this.handleBeforeUnload();
    });
    window.addEventListener('focus', () => {
      this.updateActivity();
    });
 
    // Activity detection events
    const activityEvents = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click'];
    activityEvents.forEach(event => {
      document.addEventListener(event, () => {
        this.updateActivity();
      }, {
        passive: true
      });
    });
  }
 
  /**
   * Create a new session
   */
  async createSession() {
    let userId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    const sessionId = this.generateSessionId();
    const session = {
      id: sessionId,
      userId: userId,
      createdAt: Date.now(),
      lastActivity: Date.now(),
      expiresAt: Date.now() + this.sessionTimeout,
      isActive: true,
      metadata: {
        userAgent: navigator.userAgent,
        timestamp: new Date().toISOString(),
        url: window.location.href
      }
    };
    this.activeSessions.set(sessionId, session);
    this.currentSession = session;
 
    // Cleanup old sessions if needed
    if (this.activeSessions.size > this.config.maxSessions) {
      this.cleanupOldSessions();
    }
    this.logger.info('Session created', {
      sessionId,
      userId,
      totalSessions: this.activeSessions.size
    });
    this.eventBus.emit('session:created', {
      session
    });
    return session;
  }
 
  /**
   * Update session activity
   */
  updateActivity() {
    if (!this.currentSession) return;
    const now = Date.now();
    this.currentSession.lastActivity = now;
    this.currentSession.expiresAt = now + this.sessionTimeout;
 
    // Update in sessions map
    this.activeSessions.set(this.currentSession.id, this.currentSession);
    this.logger.debug('Session activity updated', {
      sessionId: this.currentSession.id,
      lastActivity: new Date(now).toISOString()
    });
    this.eventBus.emit('session:activity', {
      sessionId: this.currentSession.id,
      timestamp: now
    });
  }
 
  /**
   * Handle user login
   */
  async handleLogin(data) {
    if (this.currentSession) {
      this.currentSession.userId = data.userId;
      this.currentSession.lastActivity = Date.now();
      this.activeSessions.set(this.currentSession.id, this.currentSession);
    } else {
      await this.createSession(data.userId);
    }
    this.logger.info('User logged in', {
      userId: data.userId,
      sessionId: this.currentSession?.id
    });
    this.eventBus.emit('session:login', {
      userId: data.userId,
      sessionId: this.currentSession?.id
    });
  }
 
  /**
   * Handle user logout
   */
  handleLogout() {
    if (this.currentSession) {
      this.endSession(this.currentSession.id);
    }
    this.logger.info('User logged out');
    this.eventBus.emit('session:logout');
  }
 
  /**
   * End a session
   */
  endSession(sessionId) {
    const session = this.activeSessions.get(sessionId);
    if (session) {
      session.isActive = false;
      session.endedAt = Date.now();
      this.activeSessions.delete(sessionId);
      if (this.currentSession && this.currentSession.id === sessionId) {
        this.currentSession = null;
      }
      this.logger.info('Session ended', {
        sessionId
      });
      this.eventBus.emit('session:ended', {
        sessionId,
        session
      });
    }
  }
 
  /**
   * Start activity monitoring
   */
  startActivityMonitoring() {
    if (this.activityTimer) {
      clearInterval(this.activityTimer);
    }
    this.activityTimer = setInterval(() => {
      this.checkSessionExpiry();
    }, this.config.activityCheckInterval);
    this.logger.debug('Activity monitoring started');
  }
 
  /**
   * Check for expired sessions
   */
  checkSessionExpiry() {
    const now = Date.now();
    const expiredSessions = [];
    this.activeSessions.forEach((session, sessionId) => {
      if (session.expiresAt < now) {
        expiredSessions.push(sessionId);
      }
    });
    expiredSessions.forEach(sessionId => {
      this.logger.info('Session expired', {
        sessionId
      });
      this.endSession(sessionId);
      this.eventBus.emit('session:expired', {
        sessionId
      });
    });
    if (expiredSessions.length > 0) {
      this.logger.info('Expired sessions cleaned up', {
        count: expiredSessions.length
      });
    }
  }
 
  /**
   * Start cleanup process
   */
  startCleanupProcess() {
    if (!this.config.autoCleanup) return;
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval);
    }
 
    // Run cleanup every 5 minutes
    this.cleanupInterval = setInterval(() => {
      this.cleanupOldSessions();
    }, 5 * 60 * 1000);
    this.logger.debug('Cleanup process started');
  }
 
  /**
   * Cleanup old sessions
   */
  cleanupOldSessions() {
    const sessions = Array.from(this.activeSessions.values());
    const sortedSessions = sessions.sort((a, b) => b.lastActivity - a.lastActivity);
 
    // Keep only the most recent sessions up to maxSessions
    const sessionsToRemove = sortedSessions.slice(this.config.maxSessions);
    sessionsToRemove.forEach(session => {
      this.endSession(session.id);
    });
    if (sessionsToRemove.length > 0) {
      this.logger.info('Old sessions cleaned up', {
        count: sessionsToRemove.length
      });
    }
  }
 
  /**
   * Update configuration
   */
  updateConfiguration(newConfig) {
    this.config = {
      ...this.config,
      ...newConfig
    };
    this.sessionTimeout = this.config.sessionTimeout;
 
    // Restart monitoring with new config
    this.startActivityMonitoring();
    this.startCleanupProcess();
    this.logger.info('Session configuration updated', this.config);
    this.eventBus.emit('session:config-updated', this.config);
  }
 
  /**
   * Handle before unload
   */
  handleBeforeUnload() {
    if (this.currentSession) {
      // Mark session as potentially ending
      this.eventBus.emit('session:before-unload', {
        sessionId: this.currentSession.id
      });
    }
  }
 
  /**
   * Generate unique session ID
   */
  generateSessionId() {
    const timestamp = Date.now().toString(36);
    const random = Math.random().toString(36).substr(2, 9);
    return `session_${timestamp}_${random}`;
  }
 
  /**
   * Get current session
   */
  getCurrentSession() {
    return this.currentSession;
  }
 
  /**
   * Get session by ID
   */
  getSession(sessionId) {
    return this.activeSessions.get(sessionId);
  }
 
  /**
   * Get all active sessions
   */
  getActiveSessions() {
    return Array.from(this.activeSessions.values());
  }
 
  /**
   * Get active session count
   */
  getActiveSessionCount() {
    return this.activeSessions.size;
  }
 
  /**
   * Get session statistics
   */
  getSessionStats() {
    const sessions = this.getActiveSessions();
    const now = Date.now();
    return {
      totalSessions: sessions.length,
      activeSessions: sessions.filter(s => s.isActive).length,
      expiredSessions: sessions.filter(s => s.expiresAt < now).length,
      averageSessionDuration: this.calculateAverageSessionDuration(sessions),
      oldestSession: sessions.reduce((oldest, session) => !oldest || session.createdAt < oldest.createdAt ? session : oldest, null),
      newestSession: sessions.reduce((newest, session) => !newest || session.createdAt > newest.createdAt ? session : newest, null)
    };
  }
 
  /**
   * Calculate average session duration
   */
  calculateAverageSessionDuration(sessions) {
    if (sessions.length === 0) return 0;
    const totalDuration = sessions.reduce((total, session) => {
      const endTime = session.endedAt || Date.now();
      return total + (endTime - session.createdAt);
    }, 0);
    return Math.round(totalDuration / sessions.length);
  }
 
  /**
   * Export session data
   */
  exportSessionData() {
    const sessions = this.getActiveSessions();
    const stats = this.getSessionStats();
    return {
      currentSession: this.currentSession,
      sessions: sessions.map(session => ({
        ...session,
        duration: (session.endedAt || Date.now()) - session.createdAt
      })),
      statistics: stats,
      configuration: this.config,
      exportedAt: new Date().toISOString()
    };
  }
 
  /**
   * Destroy the session subsystem
   */
  destroy() {
    // Clear timers
    if (this.activityTimer) {
      clearInterval(this.activityTimer);
      this.activityTimer = null;
    }
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval);
      this.cleanupInterval = null;
    }
 
    // End all sessions
    this.activeSessions.forEach((session, sessionId) => {
      this.endSession(sessionId);
    });
    this.currentSession = null;
    this.activeSessions.clear();
    this.logger.info('Session Subsystem destroyed');
    this.eventBus.emit('session:destroyed');
  }
}
 
// Export for ES modules
exports.SessionSubsystem = SessionSubsystem;
var _default = exports.default = SessionSubsystem;
 
},{}],63:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SettingsManager = void 0;
var _winstonLogger = require("./winston-logger.js");
var _cryptoUtils = require("./crypto-utils.js");
/**
 * @fileoverview Settings Manager Class
 * 
 * Manages application settings with secure storage and encryption.
 * Handles API credentials, user preferences, and configuration data
 * with automatic encryption for sensitive information.
 * 
 * @param {Object} logger - Winston logger instance for debugging
 */
 
class SettingsManager {
  /**
   * Create a new SettingsManager instance
   * @param {Object} logger - Winston logger instance for debugging
   */
  constructor() {
    let logger = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    // Initialize settings with default values
    this.settings = this.getDefaultSettings();
    this.storageKey = 'pingone-import-settings';
    this.encryptionKey = null;
 
    // Initialize Winston logger for debugging and error reporting
    this.initializeLogger(logger);
 
    // Encryption will be initialized in the init method
    this.encryptionInitialized = false;
  }
 
  /**
   * Initialize the settings manager
   * @returns {Promise<void>}
   */
  async init() {
    try {
      await this.initializeEncryption();
      this.encryptionInitialized = true;
      this.logger.info('Settings manager initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize settings manager', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Initialize Winston logger
   * @param {Object} logger - Logger instance
   */
  initializeLogger(logger) {
    if (logger && typeof logger.child === 'function') {
      this.logger = logger.child({
        component: 'settings-manager'
      });
    } else {
      this.logger = (0, _winstonLogger.createWinstonLogger)({
        service: 'pingone-import-settings',
        environment: process.env.NODE_ENV || 'development'
      });
    }
  }
 
  /**
   * Create a default console logger if none provided
   * @returns {Object} Default logger object
   */
  createDefaultLogger() {
    var _this = this;
    return {
      log: function (msg) {
        let level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
        return _this.logger.log(level, `[Settings] ${msg}`);
      },
      info: msg => this.logger.info(`[Settings] ${msg}`),
      warn: msg => this.logger.warn(`[Settings] ${msg}`),
      error: msg => this.logger.error(`[Settings] ${msg}`),
      debug: msg => this.logger.debug(`[Settings] ${msg}`)
    };
  }
 
  /**
   * Get region info by code
   * @param {string} code - Region code (e.g., 'NA', 'CA', 'EU', 'AU', 'SG', 'AP')
   * @returns {{code: string, tld: string, label: string}} Region information
   */
  static getRegionInfo(code) {
    if (!code) {
      return {
        code: 'NA',
        tld: 'com',
        label: 'North America (excluding Canada)'
      };
    }
    const regions = {
      NA: {
        code: 'NA',
        tld: 'com',
        label: 'North America (excluding Canada)'
      },
      CA: {
        code: 'CA',
        tld: 'ca',
        label: 'Canada'
      },
      EU: {
        code: 'EU',
        tld: 'eu',
        label: 'European Union'
      },
      AU: {
        code: 'AU',
        tld: 'com.au',
        label: 'Australia'
      },
      SG: {
        code: 'SG',
        tld: 'sg',
        label: 'Singapore'
      },
      AP: {
        code: 'AP',
        tld: 'asia',
        label: 'Asia-Pacific'
      }
    };
    return regions[code] || regions['NA'];
  }
 
  /**
   * Get default settings
   * @returns {Object} Default settings object
   */
  getDefaultSettings() {
    return {
      environmentId: '',
      region: 'NA',
      apiClientId: '',
      populationId: '',
      rateLimit: 50,
      connectionStatus: 'disconnected',
      connectionMessage: 'Not connected',
      lastConnectionTest: null,
      autoSave: true,
      lastUsedDirectory: '',
      theme: 'light',
      pageSize: 50,
      showNotifications: true
    };
  }
 
  /**
   * Load settings from storage
   * @returns {Promise<Object>} Loaded settings
   */
  async loadSettings() {
    try {
      const storedData = localStorage.getItem(this.storageKey);
      if (!storedData) {
        this.logger.info('No stored settings found, using defaults');
        return this.settings;
      }
 
      // Try to parse as JSON first (unencrypted)
      try {
        const parsedSettings = JSON.parse(storedData);
        this.settings = {
          ...this.getDefaultSettings(),
          ...parsedSettings
        };
        this.logger.info('Settings loaded successfully (unencrypted)', {
          hasEnvironmentId: !!this.settings.environmentId,
          hasApiClientId: !!this.settings.apiClientId,
          region: this.settings.region
        });
        return this.settings;
      } catch (jsonError) {
        // If JSON parsing fails, try decryption
        if (!this.encryptionInitialized) {
          this.logger.warn('Encryption not initialized and JSON parsing failed, using defaults');
          return this.settings;
        }
        try {
          const decryptedData = await _cryptoUtils.CryptoUtils.decrypt(storedData, this.encryptionKey);
          const parsedSettings = JSON.parse(decryptedData);
 
          // Merge with defaults to ensure all properties exist
          this.settings = {
            ...this.getDefaultSettings(),
            ...parsedSettings
          };
          this.logger.info('Settings loaded successfully (encrypted)', {
            hasEnvironmentId: !!this.settings.environmentId,
            hasApiClientId: !!this.settings.apiClientId,
            region: this.settings.region
          });
          return this.settings;
        } catch (decryptionError) {
          this.logger.error('Failed to decrypt settings', {
            error: decryptionError.message
          });
          // Return default settings on decryption error
          return this.settings;
        }
      }
    } catch (error) {
      this.logger.error('Failed to load settings', {
        error: error.message
      });
      // Return default settings on error
      return this.settings;
    }
  }
 
  /**
   * Save settings to storage
   * @param {Object} settings - Settings to save (optional)
   * @returns {Promise<void>}
   */
  async saveSettings() {
    let settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    try {
      if (settings) {
        this.settings = {
          ...this.settings,
          ...settings
        };
      }
      const jsonData = JSON.stringify(this.settings);
      if (!this.encryptionInitialized) {
        this.logger.warn('Encryption not initialized, saving settings without encryption');
        localStorage.setItem(this.storageKey, jsonData);
        this.logger.info('Settings saved successfully (unencrypted)', {
          hasEnvironmentId: !!this.settings.environmentId,
          hasApiClientId: !!this.settings.apiClientId,
          region: this.settings.region
        });
        window.dispatchEvent(new CustomEvent('settings:save-success', {
          detail: {
            message: 'Settings saved successfully (unencrypted).'
          }
        }));
        return;
      }
      try {
        const encryptedData = await _cryptoUtils.CryptoUtils.encrypt(jsonData, this.encryptionKey);
        localStorage.setItem(this.storageKey, encryptedData);
        this.logger.info('Settings saved successfully (encrypted)', {
          hasEnvironmentId: !!this.settings.environmentId,
          hasApiClientId: !!this.settings.apiClientId,
          region: this.settings.region
        });
        window.dispatchEvent(new CustomEvent('settings:save-success', {
          detail: {
            message: 'Settings saved successfully.'
          }
        }));
      } catch (encryptionError) {
        this.logger.warn('Encryption failed, saving settings without encryption', {
          error: encryptionError.message
        });
        localStorage.setItem(this.storageKey, jsonData);
        this.logger.info('Settings saved successfully (unencrypted fallback)', {
          hasEnvironmentId: !!this.settings.environmentId,
          hasApiClientId: !!this.settings.apiClientId,
          region: this.settings.region
        });
        window.dispatchEvent(new CustomEvent('settings:save-success', {
          detail: {
            message: 'Settings saved successfully (encryption failed, used fallback).'
          }
        }));
      }
    } catch (error) {
      this.logger.error('Failed to save settings', {
        error: error.message
      });
      window.dispatchEvent(new CustomEvent('settings:save-error', {
        detail: {
          message: `Failed to save settings: ${error.message}`
        }
      }));
      throw error;
    }
  }
 
  /**
   * Get a specific setting
   * @param {string} key - Setting key
   * @returns {*} Setting value
   */
  getSetting(key) {
    if (!key) {
      throw new Error('Setting key is required');
    }
    return this.settings[key];
  }
 
  /**
   * Set a specific setting
   * @param {string} key - Setting key
   * @param {*} value - Setting value
   * @returns {Promise<void>}
   */
  async setSetting(key, value) {
    if (!key) {
      throw new Error('Setting key is required');
    }
    try {
      this.settings[key] = value;
      await this.saveSettings();
      this.logger.debug('Setting updated', {
        key,
        value: typeof value === 'string' ? value : '[object]'
      });
    } catch (error) {
      this.logger.error('Failed to update setting', {
        key,
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Get all settings
   * @returns {Object} All settings
   */
  getAllSettings() {
    return {
      ...this.settings
    };
  }
 
  /**
   * Update multiple settings at once
   * @param {Object} newSettings - New settings to update
   * @returns {Promise<void>}
   */
  async updateSettings(newSettings) {
    if (!newSettings || typeof newSettings !== 'object') {
      throw new Error('New settings object is required');
    }
    try {
      this.settings = {
        ...this.settings,
        ...newSettings
      };
      await this.saveSettings();
      this.logger.info('Multiple settings updated', {
        updatedKeys: Object.keys(newSettings),
        hasEnvironmentId: !!this.settings.environmentId,
        hasApiClientId: !!this.settings.apiClientId
      });
    } catch (error) {
      this.logger.error('Failed to update settings', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Reset settings to defaults
   * @returns {Promise<void>}
   */
  async resetSettings() {
    try {
      this.settings = this.getDefaultSettings();
      await this.saveSettings();
      this.logger.info('Settings reset to defaults');
    } catch (error) {
      this.logger.error('Failed to reset settings', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Clear all settings
   * @returns {Promise<void>}
   */
  async clearSettings() {
    try {
      localStorage.removeItem(this.storageKey);
      this.settings = this.getDefaultSettings();
      this.logger.info('Settings cleared');
    } catch (error) {
      this.logger.error('Failed to clear settings', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Initialize encryption with a key derived from browser and user-specific data
   * @returns {Promise<void>}
   */
  async initializeEncryption() {
    try {
      let deviceId = await this.getDeviceId();
      if (typeof deviceId !== 'string') deviceId = String(deviceId || '');
      if (!deviceId) deviceId = 'fallback-device-id';
      this.encryptionKey = await _cryptoUtils.CryptoUtils.generateKey(deviceId);
      this.logger.debug('Encryption initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize encryption', {
        error: error.message
      });
      // Fallback to a less secure but functional approach
      this.encryptionKey = await _cryptoUtils.CryptoUtils.generateKey('fallback-encryption-key');
      this.logger.warn('Using fallback encryption key');
    }
  }
 
  /**
   * Generate a device ID based on browser and system information
   * @returns {Promise<string>} A unique device ID
   */
  async getDeviceId() {
    try {
      // Try to get a stored device ID first
      if (this.isLocalStorageAvailable()) {
        const storedDeviceId = localStorage.getItem('pingone-device-id');
        if (storedDeviceId && typeof storedDeviceId === 'string') {
          return storedDeviceId;
        }
      }
 
      // Generate device ID from browser info
      const navigatorInfo = {
        userAgent: navigator.userAgent,
        platform: navigator.platform,
        hardwareConcurrency: navigator.hardwareConcurrency,
        deviceMemory: navigator.deviceMemory,
        maxTouchPoints: navigator.maxTouchPoints
      };
      const encoder = new TextEncoder();
      const data = encoder.encode(JSON.stringify(navigatorInfo));
      const hashBuffer = await crypto.subtle.digest('SHA-256', data);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const deviceId = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
      if (typeof deviceId !== 'string' || !deviceId) {
        return 'fallback-device-id';
      }
      return deviceId;
    } catch (error) {
      this.logger.error('Failed to generate device ID:', error);
      // Fallback to a random string if crypto API fails
      return 'fallback-' + Math.random().toString(36).substring(2, 15);
    }
  }
 
  /**
   * Check if localStorage is available
   * @returns {boolean} True if localStorage is available
   */
  isLocalStorageAvailable() {
    try {
      const test = 'test';
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
    } catch (error) {
      this.logger.warn('localStorage not available', {
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Export settings (for backup)
   * @returns {Promise<Object>} Export data
   */
  async exportSettings() {
    try {
      const exportData = {
        settings: this.settings,
        exportDate: new Date().toISOString(),
        version: '1.0'
      };
      this.logger.info('Settings exported', {
        exportDate: exportData.exportDate
      });
      return exportData;
    } catch (error) {
      this.logger.error('Failed to export settings', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Import settings (from backup)
   * @param {Object} importData - Import data object
   * @returns {Promise<void>}
   */
  async importSettings(importData) {
    if (!importData) {
      throw new Error('Import data is required');
    }
    if (!importData.settings) {
      throw new Error('Invalid import data: missing settings');
    }
    try {
      this.settings = {
        ...this.getDefaultSettings(),
        ...importData.settings
      };
      await this.saveSettings();
      this.logger.info('Settings imported successfully', {
        importDate: importData.exportDate,
        hasEnvironmentId: !!this.settings.environmentId,
        hasApiClientId: !!this.settings.apiClientId
      });
    } catch (error) {
      this.logger.error('Failed to import settings', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Debug method to check localStorage contents
   * @returns {Object|null} Debug information
   */
  debugLocalStorage() {
    try {
      const storedData = localStorage.getItem(this.storageKey);
      if (!storedData) {
        this.logger.info('No data found in localStorage', {
          key: this.storageKey
        });
        return null;
      }
      this.logger.info('localStorage contents found', {
        key: this.storageKey,
        length: storedData.length,
        preview: storedData.substring(0, 100) + (storedData.length > 100 ? '...' : '')
      });
 
      // Try to parse as JSON
      try {
        const parsed = JSON.parse(storedData);
        this.logger.info('Data is valid JSON', {
          keys: Object.keys(parsed),
          hasEnvironmentId: !!parsed.environmentId,
          hasApiClientId: !!parsed.apiClientId
        });
        return parsed;
      } catch (jsonError) {
        this.logger.info('Data is not valid JSON, likely encrypted', {
          error: jsonError.message
        });
        return 'encrypted';
      }
    } catch (error) {
      this.logger.error('Failed to debug localStorage', {
        error: error.message
      });
      return null;
    }
  }
}
 
// Export the SettingsManager class
exports.SettingsManager = SettingsManager;
 
}).call(this)}).call(this,require('_process'))
},{"./crypto-utils.js":45,"./winston-logger.js":70,"_process":29}],64:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SettingsSubsystem = void 0;
/**
 * Settings Management Subsystem
 * 
 * Handles all settings operations with proper separation of concerns.
 * Manages settings form validation, saving, and UI feedback.
 */
 
class SettingsSubsystem {
  constructor(logger, uiManager, localClient, settingsManager, eventBus, credentialsManager) {
    this.logger = logger;
    this.uiManager = uiManager;
    this.localClient = localClient;
    this.settingsManager = settingsManager;
    this.eventBus = eventBus;
    this.credentialsManager = credentialsManager;
 
    // Settings state management
    this.isSaving = false;
    this.currentSettings = null;
    this.logger.info('Settings Subsystem initialized');
 
    // Set up event listeners for cross-subsystem communication
    this.setupCrossSubsystemEvents();
  }
 
  /**
   * Initialize the settings subsystem
   */
  async init() {
    try {
      this.setupEventListeners();
      await this.loadCurrentSettings();
      this.logger.info('Settings Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Settings Subsystem', error);
      this.uiManager.showSettingsActionStatus('Failed to initialize Settings Subsystem: ' + error.message, 'error');
    }
  }
 
  /**
   * Set up event listeners for settings-related elements
   */
  setupEventListeners() {
    this.logger.info('Setting up Settings Subsystem event listeners');
 
    // Save settings button
    const saveBtn = document.getElementById('save-settings');
    if (saveBtn) {
      this.logger.info('Found save settings button, attaching event listener');
      saveBtn.addEventListener('click', async e => {
        e.preventDefault();
        this.logger.info('Save settings button clicked');
        await this.saveSettings();
      });
    } else {
      this.logger.warn('Save settings button not found in DOM');
    }
 
    // Test connection button
    const testBtn = document.getElementById('test-connection-btn');
    if (testBtn) {
      testBtn.addEventListener('click', async e => {
        e.preventDefault();
        await this.testConnection();
      });
    }
 
    // Get token button
    const tokenBtn = document.getElementById('get-token-btn');
    if (tokenBtn) {
      tokenBtn.addEventListener('click', async e => {
        e.preventDefault();
        await this.getToken();
      });
    }
 
    // API secret visibility toggle
    const toggleBtn = document.getElementById('toggle-api-secret-visibility');
    if (toggleBtn) {
      toggleBtn.addEventListener('click', e => {
        e.preventDefault();
        this.toggleSecretVisibility();
      });
    }
    this.logger.info('Settings Subsystem event listeners setup complete');
  }
 
  /**
   * Load current settings from settings manager
   */
  async loadCurrentSettings() {
    try {
      // Check if settingsManager exists and has getSettings method
      if (!this.settingsManager) {
        this.logger.warn('Settings manager not available, using default settings');
        this.currentSettings = this.getDefaultSettings();
        return;
      }
      if (typeof this.settingsManager.getAllSettings !== 'function') {
        this.logger.warn('Settings manager getAllSettings method not available, using default settings');
        this.currentSettings = this.getDefaultSettings();
        return;
      }
 
      // Try to load settings from settings manager
      this.currentSettings = this.settingsManager.getAllSettings();
 
      // If settings are null or empty, use defaults
      if (!this.currentSettings || Object.keys(this.currentSettings).length === 0) {
        this.logger.info('No existing settings found, using defaults');
        this.currentSettings = this.getDefaultSettings();
      }
      this.populateSettingsForm(this.currentSettings);
      this.logger.info('Current settings loaded successfully');
    } catch (error) {
      this.logger.warn('Failed to load current settings, using defaults:', error.message);
      // Don't throw error, use default settings instead
      this.currentSettings = this.getDefaultSettings();
    }
  }
 
  /**
   * Get default settings
   */
  getDefaultSettings() {
    return {
      environmentId: '',
      apiClientId: '',
      apiSecret: '',
      region: 'NorthAmerica',
      rateLimit: 50,
      populationId: ''
    };
  }
 
  /**
   * Save settings
   */
  async saveSettings() {
    if (this.isSaving) {
      this.logger.warn('Settings save already in progress');
      return;
    }
    try {
      this.isSaving = true;
      this.logger.info('Starting settings save process');
 
      // Show immediate feedback
      this.uiManager.showSettingsActionStatus('Saving settings...', 'info');
 
      // Get form data
      const settings = this.getFormData();
      this.logger.info('Form data extracted:', settings);
 
      // Validate settings
      if (!this.validateSettings(settings)) {
        return;
      }
 
      // Save to credentials manager if available
      if (this.credentialsManager) {
        const credentials = {
          environmentId: settings.environmentId || '',
          apiClientId: settings.apiClientId || '',
          apiSecret: settings.apiSecret || '',
          populationId: settings.populationId || '',
          region: settings.region || 'NorthAmerica'
        };
        const validation = this.credentialsManager.validateCredentials(credentials);
        if (!validation.isValid) {
          throw new Error(`Invalid credentials: ${validation.errors.join(', ')}`);
        }
        this.credentialsManager.saveCredentials(credentials);
        this.logger.info('Credentials saved to localStorage');
      }
 
      // Save to server
      try {
        const response = await this.localClient.post('/api/settings', settings);
        this.logger.info('Settings saved to server successfully');
      } catch (serverError) {
        this.logger.warn('Failed to save to server, but credentials saved to localStorage:', serverError.message);
      }
 
      // Update settings manager
      this.settingsManager.updateSettings(settings);
      this.currentSettings = settings;
 
      // Show success feedback
      this.uiManager.showSettingsActionStatus('Settings saved successfully', 'success', {
        autoHideDelay: 3000
      });
 
      // Update connection status
      this.updateConnectionStatus('✅ Settings saved! Please - Get token', 'success');
 
      // Emit event for other subsystems
      if (this.eventBus) {
        this.eventBus.emit('settingsSaved', {
          settings
        });
      }
 
      // Emit credentials-updated event for population dropdown fallback system
      const credentialsUpdatedEvent = new CustomEvent('credentials-updated', {
        detail: {
          settings,
          timestamp: Date.now()
        }
      });
      document.dispatchEvent(credentialsUpdatedEvent);
      this.logger.info('Credentials-updated event dispatched for population dropdown system');
      this.logger.info('Settings save process completed successfully');
    } catch (error) {
      this.logger.error('Failed to save settings', error);
      this.uiManager.showSettingsActionStatus('Failed to save settings: ' + error.message, 'error', {
        autoHide: false
      });
    } finally {
      this.isSaving = false;
    }
  }
 
  /**
   * Get form data from settings form
   */
  getFormData() {
    const form = document.getElementById('settings-form');
    if (!form) {
      throw new Error('Settings form not found');
    }
    const formData = new FormData(form);
    const settings = {
      environmentId: document.getElementById('environment-id')?.value || '',
      apiClientId: document.getElementById('api-client-id')?.value || '',
      apiSecret: document.getElementById('api-secret')?.value || '',
      region: document.getElementById('region')?.value || 'NorthAmerica',
      rateLimit: parseInt(document.getElementById('rate-limit')?.value) || 50,
      populationId: document.getElementById('population-id')?.value || ''
    };
    return settings;
  }
 
  /**
   * Validate settings
   */
  validateSettings(settings) {
    const errors = [];
    if (!settings.environmentId?.trim()) {
      errors.push('Environment ID is required');
    }
    if (!settings.apiClientId?.trim()) {
      errors.push('API Client ID is required');
    }
    if (!settings.apiSecret?.trim()) {
      errors.push('API Secret is required');
    }
    if (!settings.region?.trim()) {
      errors.push('Region is required');
    }
    if (settings.rateLimit && (settings.rateLimit < 1 || settings.rateLimit > 1000)) {
      errors.push('Rate limit must be between 1 and 1000');
    }
    if (errors.length > 0) {
      const errorMessage = 'Validation failed: ' + errors.join(', ');
      this.logger.error('Settings validation failed', {
        errors
      });
      this.uiManager.showSettingsActionStatus(errorMessage, 'error', {
        autoHide: false
      });
      return false;
    }
    return true;
  }
 
  /**
   * Populate settings form with current values
   */
  populateSettingsForm(settings) {
    if (!settings) return;
    const fields = {
      'environment-id': settings.environmentId,
      'api-client-id': settings.apiClientId,
      'api-secret': settings.apiSecret,
      'region': settings.region,
      'rate-limit': settings.rateLimit,
      'population-id': settings.populationId
    };
    Object.entries(fields).forEach(_ref => {
      let [fieldId, value] = _ref;
      const field = document.getElementById(fieldId);
      if (field && value !== undefined && value !== null) {
        field.value = value;
      }
    });
    this.logger.info('Settings form populated with current values');
  }
 
  /**
   * Test connection
   * CRITICAL: This method MUST use GET /api/pingone/test-connection endpoint
   * DO NOT change to POST or different endpoint without updating server-side route
   * Last fixed: 2025-07-22 - Fixed HTTP method mismatch causing 400 Bad Request errors
   */
  async testConnection() {
    try {
      this.logger.info('Testing connection...');
      this.uiManager.showSettingsActionStatus('Testing connection...', 'info');
      const settings = this.getFormData();
 
      // Test connection via API
      // CRITICAL: Use GET request to match server-side endpoint
      // Server endpoint: routes/pingone-proxy-fixed.js - router.get('/test-connection')
      // DO NOT change to POST without updating server-side endpoint
      // Last fixed: 2025-07-22 - HTTP method mismatch caused 400 Bad Request errors
      const response = await this.localClient.get('/api/pingone/test-connection');
      if (response.success) {
        this.uiManager.showSettingsActionStatus('Connection test successful', 'success', {
          autoHideDelay: 3000
        });
        this.updateConnectionStatus('✅ Connection successful', 'success');
      } else {
        this.uiManager.showSettingsActionStatus('Connection test failed: ' + response.message, 'error');
        this.updateConnectionStatus('❌ Connection failed', 'error');
      }
    } catch (error) {
      this.logger.error('Connection test failed', error);
      this.uiManager.showSettingsActionStatus('Connection test failed: ' + error.message, 'error');
      this.updateConnectionStatus('❌ Connection failed', 'error');
    }
  }
 
  /**
   * Get token
   */
  async getToken() {
    try {
      this.logger.info('Getting token...');
      this.uiManager.showSettingsActionStatus('Getting token...', 'info');
      const settings = this.getFormData();
 
      // Get token via API
      const response = await this.localClient.post('/api/token', settings);
      if (response.success) {
        this.uiManager.showSettingsActionStatus('Token obtained successfully', 'success', {
          autoHideDelay: 3000
        });
        this.updateConnectionStatus('✅ Token obtained', 'success');
 
        // NEW: Direct global token status updater for sidebar
        console.log('🚀 [DEBUG] SettingsSubsystem: About to call updateGlobalTokenStatusDirect');
        try {
          // Get the main app instance to call the direct updater
          if (window.app && typeof window.app.updateGlobalTokenStatusDirect === 'function') {
            // Calculate time left from token response
            const timeLeft = response.timeLeft || response.timeRemaining || '';
            window.app.updateGlobalTokenStatusDirect(timeLeft);
            console.log('✅ [DEBUG] SettingsSubsystem: updateGlobalTokenStatusDirect called successfully with timeLeft:', timeLeft);
          } else {
            console.warn('⚠️ [DEBUG] SettingsSubsystem: window.app.updateGlobalTokenStatusDirect not available');
          }
        } catch (error) {
          console.error('❌ [DEBUG] SettingsSubsystem: Error calling updateGlobalTokenStatusDirect:', error);
        }
 
        // Emit event for other subsystems
        if (this.eventBus) {
          this.eventBus.emit('tokenObtained', {
            token: response.token
          });
        }
      } else {
        this.uiManager.showSettingsActionStatus('Failed to get token: ' + response.message, 'error');
        this.updateConnectionStatus('❌ Token failed', 'error');
      }
    } catch (error) {
      this.logger.error('Failed to get token', error);
      this.uiManager.showSettingsActionStatus('Failed to get token: ' + error.message, 'error');
      this.updateConnectionStatus('❌ Token failed', 'error');
    }
  }
 
  /**
   * Toggle API secret visibility
   */
  toggleSecretVisibility() {
    const secretField = document.getElementById('api-secret');
    const toggleBtn = document.getElementById('toggle-api-secret-visibility');
    const icon = toggleBtn?.querySelector('i');
    if (secretField && toggleBtn && icon) {
      if (secretField.type === 'password') {
        secretField.type = 'text';
        icon.className = 'fas fa-eye-slash';
        toggleBtn.setAttribute('aria-label', 'Hide password');
      } else {
        secretField.type = 'password';
        icon.className = 'fas fa-eye';
        toggleBtn.setAttribute('aria-label', 'Show password');
      }
    }
  }
 
  /**
   * Update connection status display
   */
  updateConnectionStatus(message, type) {
    const statusElement = document.getElementById('settings-connection-status');
    if (statusElement) {
      statusElement.textContent = message;
      statusElement.className = `connection-status status-${type}`;
    }
  }
 
  /**
   * Set up cross-subsystem event listeners
   */
  setupCrossSubsystemEvents() {
    if (!this.eventBus) {
      this.logger.warn('EventBus not available for cross-subsystem events');
      return;
    }
 
    // Listen for token expiration events
    this.eventBus.on('tokenExpired', data => {
      this.logger.warn('Token expired');
      this.updateConnectionStatus('⚠️ Token expired', 'warning');
    });
 
    // Listen for token error events
    this.eventBus.on('tokenError', data => {
      this.logger.error('Token error detected', data);
      this.updateConnectionStatus('❌ Token error', 'error');
    });
 
    // Listen for token refresh events
    this.eventBus.on('tokenRefreshed', data => {
      this.logger.info('Token refreshed successfully');
      this.updateConnectionStatus('✅ Token refreshed', 'success');
    });
    this.logger.debug('Cross-subsystem event listeners set up for SettingsSubsystem');
  }
 
  /**
   * Get all settings (required by App initialization)
   * @returns {Object} All current settings
   */
  getAllSettings() {
    if (this.settingsManager && this.settingsManager.getAllSettings) {
      return this.settingsManager.getAllSettings();
    } else if (this.settingsManager && this.settingsManager.getSettings) {
      return this.settingsManager.getSettings();
    } else if (this.currentSettings) {
      return this.currentSettings;
    } else {
      this.logger.warn('No settings available, returning empty object');
      return {};
    }
  }
}
exports.SettingsSubsystem = SettingsSubsystem;
 
},{}],65:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.clearTokenAlertSession = clearTokenAlertSession;
exports.showTokenAlertModal = showTokenAlertModal;
// Token Alert Modal - blocks interaction and guides user to settings if no valid token is available
class TokenAlertModal {
  constructor() {
    let {
      tokenStatus = '',
      expiry = '',
      operation = ''
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    if (TokenAlertModal.hasShownThisSession()) return;
    TokenAlertModal.setShownThisSession();
    this.operation = operation;
    this.createModal(tokenStatus, expiry);
    this.showModal();
  }
  createModal(tokenStatus, expiry) {
    // Overlay
    const overlay = document.createElement('div');
    overlay.className = 'token-alert-overlay';
    overlay.setAttribute('role', 'dialog');
    overlay.setAttribute('aria-modal', 'true');
    overlay.setAttribute('aria-labelledby', 'token-alert-title');
    overlay.setAttribute('aria-describedby', 'token-alert-content');
 
    // Modal content with enhanced styling and action button
    overlay.innerHTML = `
            <div class="token-alert-modal" tabindex="-1">
                <div class="token-alert-header">
                    <h2 id="token-alert-title">
                        <span class="warning-icon" aria-hidden="true">⚠️</span>
                        <span>Authentication Required</span>
                    </h2>
                    <button type="button" class="token-alert-close" id="token-alert-close" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="token-alert-body">
                    <div id="token-alert-content" class="token-alert-content">
                        <div class="token-alert-icon">
                            <span aria-hidden="true">🔐</span>
                        </div>
                        <h3>No Valid Token Available</h3>
                        <p class="token-alert-message">
                            <strong>Authentication is required to continue.</strong>
                            ${this.operation ? `You need valid credentials to perform the "${this.operation}" operation.` : 'You need valid credentials to use this application.'}
                        </p>
                        ${tokenStatus || expiry ? `<div class="token-status-info">
                            <p><strong>Current Status:</strong> ${tokenStatus ? tokenStatus : 'No token available'}</p>
                            ${expiry ? `<p style="visibility: hidden;"><strong>Token Expired:</strong> ${expiry}</p>` : ''}
                        </div>` : ''}
                        <div class="token-alert-actions">
                            <button type="button" class="btn btn-primary btn-lg" id="token-alert-settings-btn">
                                <span class="btn-icon">⚙️</span>
                                Go to Settings
                            </button>
                            <p class="token-alert-help">
                                Add your PingOne credentials in the Settings page to generate a new token.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    document.body.appendChild(overlay);
    this.overlay = overlay;
    this.modal = overlay.querySelector('.token-alert-modal');
    this.settingsBtn = overlay.querySelector('#token-alert-settings-btn');
    this.closeBtn = overlay.querySelector('#token-alert-close');
    this.bindEvents();
  }
  bindEvents() {
    // Settings button - navigate to settings
    this.settingsBtn.addEventListener('click', () => {
      this.hideModal();
      // Navigate to settings view within the SPA instead of redirecting
      if (window.app && window.app.showView) {
        window.app.showView('settings');
      } else {
        // Fallback: navigate to settings view by triggering the settings nav item
        const settingsNavItem = document.querySelector('[data-view="settings"]');
        if (settingsNavItem) {
          settingsNavItem.click();
        } else {
          // Final fallback: redirect to home page which will show settings
          window.location.href = '/';
        }
      }
    });
 
    // Close button - allow manual dismissal
    this.closeBtn.addEventListener('click', () => {
      this.hideModal();
    });
 
    // Trap focus within modal
    this.overlay.addEventListener('keydown', e => this.handleKeyboardNavigation(e));
 
    // Prevent closing by outside click (modal should be persistent)
    this.overlay.addEventListener('click', e => {
      if (e.target === this.overlay) {
        e.preventDefault();
        // Don't close on outside click - keep modal visible
      }
    });
 
    // Prevent escape key from closing modal (should be persistent)
    document.addEventListener('keydown', e => {
      if (e.key === 'Escape') {
        e.preventDefault();
        // Don't close on escape - keep modal visible
      }
    });
  }
  handleKeyboardNavigation(e) {
    const focusable = this.modal.querySelectorAll('button, [tabindex]:not([tabindex="-1"])');
    if (e.key === 'Tab') {
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (e.shiftKey) {
        if (document.activeElement === first) {
          e.preventDefault();
          last.focus();
        }
      } else {
        if (document.activeElement === last) {
          e.preventDefault();
          first.focus();
        }
      }
    }
  }
  showModal() {
    document.body.classList.add('token-alert-open');
    this.overlay.classList.add('active');
    this.modal.focus();
 
    // Add styles to body to prevent scrolling
    document.body.style.overflow = 'hidden';
  }
  hideModal() {
    this.overlay.classList.remove('active');
    document.body.classList.remove('token-alert-open');
    document.body.style.overflow = '';
    setTimeout(() => {
      if (this.overlay && this.overlay.parentNode) {
        this.overlay.parentNode.removeChild(this.overlay);
      }
    }, 300);
  }
  static hasShownThisSession() {
    return sessionStorage.getItem('tokenAlertModalShown') === 'true';
  }
  static setShownThisSession() {
    sessionStorage.setItem('tokenAlertModalShown', 'true');
  }
  static clearShownThisSession() {
    sessionStorage.removeItem('tokenAlertModalShown');
  }
}
 
// Export a function to show the modal
function showTokenAlertModal() {
  let {
    tokenStatus = '',
    expiry = '',
    operation = ''
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  new TokenAlertModal({
    tokenStatus,
    expiry,
    operation
  });
}
 
// Export function to clear the session flag (useful for testing)
function clearTokenAlertSession() {
  TokenAlertModal.clearShownThisSession();
}
 
},{}],66:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
/**
 * TokenManager - Handles OAuth 2.0 token acquisition and caching with automatic re-authentication
 * 
 * Features:
 * - Automatic token refresh before expiry
 * - Detection of token expiration via 401 responses
 * - Automatic retry of failed requests with new tokens
 * - Secure credential storage and retrieval
 * - Rate limiting to prevent API abuse
 */
class TokenManager {
  /**
   * Create a new TokenManager instance
   * @param {Object} logger - Logger instance for logging messages
   * @param {Object} settings - Settings object containing API credentials
   */
  constructor(logger, settings, eventBus) {
    if (!settings) {
      throw new Error('Settings are required for TokenManager');
    }
    this.logger = logger || console;
    this.settings = settings || {};
    this.eventBus = eventBus;
    this.tokenCache = {
      accessToken: null,
      expiresAt: 0,
      tokenType: 'Bearer',
      lastRefresh: 0
    };
    this.tokenExpiryBuffer = 5 * 60 * 1000; // 5 minutes buffer before token expiry
    this.isRefreshing = false;
    this.refreshQueue = [];
 
    // Auto-retry configuration
    this.maxRetries = 1; // Only retry once with new token
    this.retryDelay = 1000; // 1 second delay before retry
 
    // Bind methods
    this.getAccessToken = this.getAccessToken.bind(this);
    this._requestNewToken = this._requestNewToken.bind(this);
    this._isTokenValid = this._isTokenValid.bind(this);
    this.handleTokenExpiration = this.handleTokenExpiration.bind(this);
    this.retryWithNewToken = this.retryWithNewToken.bind(this);
  }
 
  /**
   * Get a valid access token, either from cache or by requesting a new one
   * @returns {Promise<string>} The access token
   */
  async getAccessToken() {
    // Check if we have a valid cached token
    if (this._isTokenValid()) {
      this.logger.debug('Using cached access token');
      return this.tokenCache.accessToken;
    }
 
    // If a refresh is already in progress, queue this request
    if (this.isRefreshing) {
      return new Promise(resolve => {
        this.refreshQueue.push(resolve);
      });
    }
 
    // Otherwise, request a new token
    try {
      this.isRefreshing = true;
      const token = await this._requestNewToken();
 
      // Resolve all queued requests
      while (this.refreshQueue.length > 0) {
        const resolve = this.refreshQueue.shift();
        resolve(token);
      }
      return token;
    } catch (error) {
      // Clear token cache on error
      this.tokenCache = {
        accessToken: null,
        expiresAt: 0,
        tokenType: 'Bearer',
        lastRefresh: 0
      };
 
      // Emit token error event
      if (this.eventBus) {
        this.eventBus.emit('tokenError', {
          error: error.message
        });
      }
 
      // Reject all queued requests
      while (this.refreshQueue.length > 0) {
        const resolve = this.refreshQueue.shift();
        resolve(Promise.reject(error));
      }
      throw error;
    } finally {
      this.isRefreshing = false;
    }
  }
 
  /**
   * Handle token expiration detected from API response
   * @param {Object} response - The failed API response
   * @param {Function} retryFn - Function to retry the original request
   * @returns {Promise<Object>} The retry result
   */
  async handleTokenExpiration(response, retryFn) {
    if (!response) {
      throw new Error('Response is required for token expiration handling');
    }
    if (!retryFn || typeof retryFn !== 'function') {
      throw new Error('Retry function is required for token expiration handling');
    }
    this.logger.warn('Token expiration detected, attempting automatic re-authentication');
 
    // Clear the expired token
    this.tokenCache = {
      accessToken: null,
      expiresAt: 0,
      tokenType: 'Bearer',
      lastRefresh: 0
    };
 
    // Emit token expiration event
    if (this.eventBus) {
      this.eventBus.emit('tokenExpired', {
        response
      });
    }
    try {
      // Get a new token using stored credentials
      const newToken = await this.getAccessToken();
      if (!newToken) {
        throw new Error('Failed to obtain new token for retry');
      }
      this.logger.info('Successfully obtained new token, retrying request');
 
      // Wait a moment before retrying to avoid rate limiting
      await new Promise(resolve => setTimeout(resolve, this.retryDelay));
 
      // Retry the original request with the new token
      return await retryFn(newToken);
    } catch (error) {
      this.logger.error('Failed to re-authenticate and retry request', {
        error: error.message,
        originalStatus: response.status
      });
      throw error;
    }
  }
 
  /**
   * Retry a failed request with a new token
   * @param {Function} requestFn - Function that makes the API request
   * @param {Object} options - Request options
   * @returns {Promise<Object>} The API response
   */
  async retryWithNewToken(requestFn) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    if (!requestFn || typeof requestFn !== 'function') {
      throw new Error('Request function is required for retry operation');
    }
    let retryCount = 0;
    while (retryCount <= this.maxRetries) {
      try {
        // Get current token
        const token = await this.getAccessToken();
 
        // Make the request
        const response = await requestFn(token);
 
        // Check if the response indicates token expiration
        if (response.status === 401) {
          const responseText = await response.text().catch(() => '');
          const isTokenExpired = responseText.includes('token_expired') || responseText.includes('invalid_token') || responseText.includes('expired');
          if (isTokenExpired && retryCount < this.maxRetries) {
            this.logger.warn(`Token expired on attempt ${retryCount + 1}, retrying with new token`);
 
            // Clear expired token and get new one
            this.tokenCache = {
              accessToken: null,
              expiresAt: 0,
              tokenType: 'Bearer',
              lastRefresh: 0
            };
            retryCount++;
            continue;
          }
        }
 
        // If we get here, the request was successful or we've exhausted retries
        return response;
      } catch (error) {
        if (retryCount >= this.maxRetries) {
          throw error;
        }
        this.logger.warn(`Request failed on attempt ${retryCount + 1}, retrying`, {
          error: error.message
        });
        retryCount++;
 
        // Wait before retrying
        await new Promise(resolve => setTimeout(resolve, this.retryDelay));
      }
    }
    throw new Error('Max retries exceeded');
  }
 
  /**
   * Create a request wrapper that automatically handles token expiration
   * @param {Function} requestFn - Function that makes the API request
   * @returns {Function} Wrapped function that handles token expiration
   */
  createAutoRetryWrapper(requestFn) {
    var _this = this;
    if (!requestFn || typeof requestFn !== 'function') {
      throw new Error('Request function is required for auto-retry wrapper');
    }
    return async function () {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return await _this.retryWithNewToken(async token => {
        // Add the token to the request arguments
        const requestArgs = [...args];
 
        // If the first argument is an options object, add the token to it
        if (requestArgs[0] && typeof requestArgs[0] === 'object') {
          requestArgs[0].headers = {
            ...requestArgs[0].headers,
            'Authorization': `Bearer ${token}`
          };
        }
        return await requestFn(...requestArgs);
      });
    };
  }
 
  /**
   * Get token information including expiry details
   * @returns {Object|null} Token info object or null if no token
   */
  getTokenInfo() {
    if (!this.tokenCache.accessToken) {
      return null;
    }
    const now = Date.now();
    const expiresIn = Math.max(0, this.tokenCache.expiresAt - now);
    return {
      accessToken: this.tokenCache.accessToken,
      expiresIn: Math.floor(expiresIn / 1000),
      // Convert to seconds
      tokenType: this.tokenCache.tokenType,
      expiresAt: this.tokenCache.expiresAt,
      lastRefresh: this.tokenCache.lastRefresh,
      isValid: this._isTokenValid()
    };
  }
 
  /**
   * Check if the current token is still valid
   * @returns {boolean} True if token is valid, false otherwise
   * @private
   */
  _isTokenValid() {
    const now = Date.now();
    return this.tokenCache.accessToken && this.tokenCache.expiresAt > now + this.tokenExpiryBuffer &&
    // Ensure token isn't too old (max 1 hour)
    now - this.tokenCache.lastRefresh < 60 * 60 * 1000;
  }
 
  /**
   * Get the auth domain for a given region
   * @param {string} region - The region to get auth domain for
   * @returns {string} The auth domain URL
   * @private
   */
  _getAuthDomain(region) {
    if (!region) {
      return 'auth.pingone.com';
    }
    const authDomainMap = {
      'NorthAmerica': 'auth.pingone.com',
      'Europe': 'auth.eu.pingone.com',
      'Canada': 'auth.ca.pingone.com',
      'Asia': 'auth.apsoutheast.pingone.com',
      'Australia': 'auth.aus.pingone.com',
      'US': 'auth.pingone.com',
      'EU': 'auth.eu.pingone.com',
      'AP': 'auth.apsoutheast.pingone.com'
    };
    return authDomainMap[region] || 'auth.pingone.com';
  }
 
  /**
   * Request a new access token from PingOne using stored credentials
   * @returns {Promise<string>} The new access token
   * @private
   */
  async _requestNewToken() {
    const {
      apiClientId,
      apiSecret,
      environmentId,
      region = 'NorthAmerica'
    } = this.settings;
    const requestId = `req_${Math.random().toString(36).substr(2, 9)}`;
    const startTime = Date.now();
 
    // Validate required settings
    if (!apiClientId || !apiSecret || !environmentId) {
      const error = new Error('Missing required API credentials in settings');
      this.logger.error('Token request failed: Missing credentials', {
        requestId,
        hasClientId: !!apiClientId,
        hasSecret: !!apiSecret,
        hasEnvId: !!environmentId
      });
      throw error;
    }
 
    // Prepare request
    const authDomain = this._getAuthDomain(region);
    const tokenUrl = `https://${authDomain}/${environmentId}/as/token`;
    const credentials = btoa(`${apiClientId}:${apiSecret}`);
    try {
      this.logger.debug('Requesting new access token from PingOne...', {
        requestId,
        authDomain,
        environmentId,
        region
      });
      const response = await fetch(tokenUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': `Basic ${credentials}`
        },
        body: 'grant_type=client_credentials',
        credentials: 'omit'
      });
      const responseTime = Date.now() - startTime;
      let responseData;
      try {
        responseData = await response.json();
      } catch (e) {
        const text = await response.text().catch(() => 'Failed to read response text');
        throw new Error(`Invalid JSON response: ${e.message}. Response: ${text}`);
      }
      if (!response.ok) {
        const errorMsg = responseData.error_description || responseData.error || `HTTP ${response.status} ${response.statusText}`;
        this.logger.error('Token request failed', {
          requestId,
          status: response.status,
          error: responseData.error,
          errorDescription: responseData.error_description,
          responseTime: `${responseTime}ms`,
          url: tokenUrl
        });
        throw new Error(errorMsg);
      }
      if (!responseData.access_token) {
        throw new Error('No access token in response');
      }
 
      // Update token cache
      const expiresInMs = (responseData.expires_in || 3600) * 1000;
      this.tokenCache = {
        accessToken: responseData.access_token,
        expiresAt: Date.now() + expiresInMs,
        tokenType: responseData.token_type || 'Bearer',
        lastRefresh: Date.now()
      };
      this.logger.info('Successfully obtained new access token', {
        requestId,
        tokenType: this.tokenCache.tokenType,
        expiresIn: Math.floor(expiresInMs / 1000) + 's',
        responseTime: `${responseTime}ms`
      });
 
      // Emit token refresh event
      if (this.eventBus) {
        this.eventBus.emit('tokenRefreshed', {
          tokenType: this.tokenCache.tokenType,
          expiresAt: this.tokenCache.expiresAt
        });
      }
      return this.tokenCache.accessToken;
    } catch (error) {
      this.logger.error('Error getting access token', {
        requestId,
        error: error.toString(),
        message: error.message,
        url: tokenUrl,
        responseTime: `${Date.now() - startTime}ms`
      });
 
      // Clear token cache on error
      this.tokenCache = {
        accessToken: null,
        expiresAt: 0,
        tokenType: 'Bearer',
        lastRefresh: 0
      };
      throw error;
    }
  }
 
  /**
   * Update settings and clear token cache if credentials changed
   * @param {Object} newSettings - New settings object
   */
  updateSettings(newSettings) {
    if (!newSettings) {
      throw new Error('New settings are required for update');
    }
    const credentialsChanged = newSettings.apiClientId !== this.settings.apiClientId || newSettings.apiSecret !== this.settings.apiSecret || newSettings.environmentId !== this.settings.environmentId || newSettings.region !== this.settings.region;
    this.settings = {
      ...this.settings,
      ...newSettings
    };
    if (credentialsChanged) {
      this.logger.debug('API credentials changed, clearing token cache');
      this.tokenCache = {
        accessToken: null,
        expiresAt: 0,
        tokenType: 'Bearer',
        lastRefresh: 0
      };
    }
  }
}
var _default = exports.default = TokenManager;
 
},{}],67:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
/**
 * Token Refresh Handler
 * 
 * Provides automatic token refresh functionality for API calls
 * with retry logic and error handling.
 */
 
class TokenRefreshHandler {
  constructor() {
    this.tokenRefreshInProgress = false;
    this.tokenRefreshPromise = null;
    this.lastRefreshTime = 0;
    this.minRefreshInterval = 5000; // 5 seconds
  }
 
  /**
   * Get a fresh token with automatic refresh if needed
   * @param {Object} tokenManager - Token manager instance
   * @returns {Promise<string>} Fresh token
   */
  async getFreshToken(tokenManager) {
    if (!tokenManager) {
      throw new Error('Token manager is required');
    }
 
    // Check if we already have a valid token
    try {
      const currentToken = await tokenManager.getAccessToken();
      if (currentToken) {
        return currentToken;
      }
    } catch (error) {
      console.warn('Error getting current token:', error);
      // Continue with refresh
    }
 
    // If refresh is already in progress, wait for it
    if (this.tokenRefreshInProgress) {
      console.log('Token refresh already in progress, waiting...');
      return this.tokenRefreshPromise;
    }
 
    // Check if we've refreshed recently
    const now = Date.now();
    if (now - this.lastRefreshTime < this.minRefreshInterval) {
      console.log('Token was refreshed recently, using cached token');
      return tokenManager.getAccessToken();
    }
 
    // Start refresh process
    this.tokenRefreshInProgress = true;
    this.tokenRefreshPromise = this._refreshToken(tokenManager);
    try {
      const token = await this.tokenRefreshPromise;
      return token;
    } finally {
      this.tokenRefreshInProgress = false;
      this.lastRefreshTime = Date.now();
    }
  }
 
  /**
   * Refresh token with retry logic
   * @private
   * @param {Object} tokenManager - Token manager instance
   * @returns {Promise<string>} Fresh token
   */
  async _refreshToken(tokenManager) {
    console.log('Refreshing token...');
 
    // Clear current token to force refresh
    if (typeof tokenManager.clearToken === 'function') {
      tokenManager.clearToken();
    }
 
    // Try to get a new token
    try {
      const token = await tokenManager.getAccessToken();
      if (!token) {
        throw new Error('Failed to get new token');
      }
      console.log('Token refreshed successfully');
      return token;
    } catch (error) {
      console.error('Failed to refresh token:', error);
      throw error;
    }
  }
 
  /**
   * Make an API call with automatic token refresh
   * @param {Function} apiCall - Function that makes the API call
   * @param {Object} tokenManager - Token manager instance
   * @param {number} maxRetries - Maximum number of retries
   * @returns {Promise<Object>} API response
   */
  async callWithTokenRefresh(apiCall, tokenManager) {
    let maxRetries = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
    let retries = 0;
    while (retries <= maxRetries) {
      try {
        // Get fresh token
        const token = await this.getFreshToken(tokenManager);
 
        // Make API call
        return await apiCall(token);
      } catch (error) {
        // Check if error is due to token expiration
        const isTokenError = error.status === 401 || error.message && error.message.includes('token');
        if (isTokenError && retries < maxRetries) {
          console.log(`Token error, retrying (${retries + 1}/${maxRetries})...`);
          retries++;
 
          // Force token refresh
          if (typeof tokenManager.clearToken === 'function') {
            tokenManager.clearToken();
          }
 
          // Wait before retry
          await new Promise(resolve => setTimeout(resolve, 1000));
        } else {
          // Rethrow error if not token related or max retries reached
          throw error;
        }
      }
    }
  }
}
 
// Create and export a singleton instance
const tokenRefreshHandler = new TokenRefreshHandler();
var _default = exports.default = tokenRefreshHandler;
 
},{}],68:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UIManager = void 0;
var _circularProgress = require("./circular-progress.js");
var _elementRegistry = require("./element-registry.js");
var _progressManager = _interopRequireDefault(require("./progress-manager.js"));
var _errorTypes = require("./error/error-types.js");
// File: ui-manager.js
// Description: UI management for PingOne user import tool
// 
// This module handles all user interface interactions and state management:
// - Status notifications and user feedback
// - Progress tracking and real-time updates
// - View transitions and navigation
// - Debug logging and error display
// - Connection status indicators
// - Form handling and validation feedback
// 
// Provides a centralized interface for updating the UI based on application events.
 
// Enable debug mode for development (set to false in production)
const DEBUG_MODE = process.env.NODE_ENV === 'development';
 
/**
 * UI Manager Class
 * 
 * Manages all user interface interactions and updates with centralized error handling.
 */
class UIManager {
  /**
   * Create a new UIManager instance
   * @param {Object} options - Configuration options
   * @param {Object} options.errorManager - Error manager instance
   * @param {Object} options.logManager - Log manager instance
   */
  constructor() {
    let {
      errorManager,
      logManager
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    // Initialize logger from logManager or fallback to console
    this.logger = logManager?.getLogger('UIManager') || console;
 
    // Initialize error manager
    this.errorManager = errorManager || {
      handleError: (error, context) => {
        console.error('Unhandled error (no error manager):', error, context);
      }
    };
 
    // Initialize UI elements
    this.notificationContainer = null;
    this.progressContainer = null;
    this.tokenStatusElement = null;
    this.connectionStatusElement = null;
 
    // Initialize the UI manager
    this.initialize();
  }
 
  /**
   * Initialize UI manager and setup core functionality
   */
  /**
   * Initialize the UI Manager
   * @private
   */
  initialize() {
    try {
      this.setupElements();
      this.logger.info('UI Manager initialized successfully');
    } catch (error) {
      this.errorManager.handleError(error, {
        component: 'UIManager',
        operation: 'initialize',
        severity: 'error',
        context: {
          message: 'Failed to initialize UI Manager',
          error: error.message
        }
      });
    }
  }
 
  /**
   * Initialize UI manager (alias for initialize for compatibility)
   * @returns {Promise<void>} Promise that resolves when initialization is complete
   */
  async init() {
    this.initialize();
    return Promise.resolve();
  }
 
  /**
   * Setup UI elements and initialize core DOM references
   */
  setupElements() {
    try {
      // Initialize core UI elements with safe fallbacks
      this.notificationContainer = _elementRegistry.ElementRegistry.notificationContainer ? _elementRegistry.ElementRegistry.notificationContainer() : null;
      this.progressContainer = _elementRegistry.ElementRegistry.progressContainer ? _elementRegistry.ElementRegistry.progressContainer() : null;
      this.tokenStatusElement = _elementRegistry.ElementRegistry.tokenStatus ? _elementRegistry.ElementRegistry.tokenStatus() : null;
      this.connectionStatusElement = _elementRegistry.ElementRegistry.connectionStatus ? _elementRegistry.ElementRegistry.connectionStatus() : null;
 
      // Initialize navigation items for safe access
      this.navItems = document.querySelectorAll('[data-view]');
      if (!this.notificationContainer) {
        this.logger.warn('Notification container not found');
      }
      if (!this.progressContainer) {
        this.logger.warn('Progress container not found');
      }
      this.logger.debug('UI elements setup completed', {
        hasNotificationContainer: !!this.notificationContainer,
        hasProgressContainer: !!this.progressContainer,
        hasTokenStatusElement: !!this.tokenStatusElement,
        hasConnectionStatusElement: !!this.connectionStatusElement,
        navItemsCount: this.navItems ? this.navItems.length : 0
      });
    } catch (error) {
      this.logger.error('Error setting up UI elements', {
        error: error.message
      });
    }
  }
 
  /**
   * Show a status message in the status bar
   * @param {string} message - The message to display
   * @param {string} [type='info'] - Message type (info, success, warning, error)
   * @param {Object} [options] - Additional options
   * @param {number} [options.duration=5000] - Duration in milliseconds to show the message
   * @param {boolean} [options.autoDismiss=true] - Whether to auto-dismiss the message
   * @param {string} [options.errorId] - Unique error ID for tracking
   * @param {Object} [options.context] - Additional context for the message
   */
  /**
   * Show a status message in the status bar
   * @param {string} message - The message to display
   * @param {string} [type='info'] - Message type (info, success, warning, error)
   * @param {Object} [options] - Additional options
   * @param {number} [options.duration=5000] - Duration in milliseconds to show the message
   * @param {boolean} [options.autoDismiss=true] - Whether to auto-dismiss the message
   * @param {string} [options.errorId] - Unique error ID for tracking
   * @param {Object} [options.context] - Additional context for the message
   */
  showStatusBar(message) {
    let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const {
      duration = 5000,
      autoDismiss = true,
      errorId,
      context = {}
    } = options;
    try {
      // Log the status message with appropriate level
      const logLevel = {
        info: 'info',
        success: 'info',
        warning: 'warn',
        error: 'error'
      }[type] || 'log';
 
      // Create log context
      const logContext = {
        messageType: type,
        ...(errorId && {
          errorId
        }),
        ...context
      };
 
      // Log the message with context
      this.logger[logLevel](`Status: ${message}`, logContext);
 
      // If status bar element is not available, just log and return
      if (!this.statusBarElement) {
        this.logger.debug('Status bar element not available in current view', logContext);
        return;
      }
 
      // Clear any existing timers
      if (this.statusBarTimer) {
        clearTimeout(this.statusBarTimer);
        this.statusBarTimer = null;
      }
 
      // Clear existing content
      this.statusBarElement.innerHTML = '';
 
      // Create message element
      const msg = document.createElement('span');
      msg.className = 'status-message';
 
      // Add error ID to the message if available
      let displayMessage = message;
      if (type === 'error' && errorId) {
        displayMessage += ` (Error ID: ${errorId})`;
 
        // In development, show more context for errors
        if (process.env.NODE_ENV === 'development' && Object.keys(context).length > 0) {
          displayMessage += `\n${JSON.stringify(context, null, 2)}`;
        }
      }
      msg.textContent = displayMessage;
      this.statusBarElement.appendChild(msg);
 
      // Add dismiss button for error/warning (persistent messages)
      if (type === 'error' || type === 'warning') {
        const dismiss = document.createElement('button');
        dismiss.className = 'status-dismiss';
        dismiss.innerHTML = '&times;';
        dismiss.setAttribute('aria-label', 'Dismiss message');
        dismiss.onclick = () => this.clearStatusBar();
        this.statusBarElement.appendChild(dismiss);
      }
 
      // Set status bar classes
      this.statusBarElement.className = `status-bar status-bar-${type} visible`;
 
      // Auto-dismiss for success/info messages or if explicitly enabled
      const shouldAutoDismiss = autoDismiss && (type === 'success' || type === 'info');
      if (shouldAutoDismiss) {
        this.statusBarTimer = setTimeout(() => {
          this.clearStatusBar();
        }, duration);
      }
    } catch (error) {
      // If there's an error showing the status bar, report it but don't crash
      this.errorManager.handleError(error, {
        component: 'UIManager',
        operation: 'showStatusBar',
        severity: 'warning',
        context: {
          originalMessage: message,
          type,
          options,
          errorMessage: error.message
        }
      });
 
      // Fallback to console if the error manager fails
      console.error('Failed to show status bar:', error);
      console.log('Original message:', message);
 
      // Try to show a simplified error message
      try {
        if (this.statusBarElement) {
          this.statusBarElement.textContent = `Error: ${message.substring(0, 100)}`;
          this.statusBarElement.className = 'status-bar status-bar-error visible';
        }
      } catch (e) {
        // If we can't even show the error message, just give up
        console.error('Completely failed to show status bar:', e);
      }
    }
  }
 
  /**
   * Clear the status bar with smooth animation
   * @param {Object} [options] - Additional options
   * @param {boolean} [options.force=false] - Force clear without animation
   */
  clearStatusBar() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    try {
      // Clear any pending auto-dismiss timers
      if (this.statusBarTimer) {
        clearTimeout(this.statusBarTimer);
        this.statusBarTimer = null;
      }
 
      // If status bar element doesn't exist, just return
      if (!this.statusBarElement) {
        this.logger.debug('Status bar element not found during clear');
        return;
      }
      const {
        force = false
      } = options;
      if (force) {
        // Immediate removal
        this.statusBarElement.innerHTML = '';
        this.statusBarElement.className = 'status-bar';
        this.logger.debug('Status bar cleared immediately');
      } else {
        // Animate out
        this.statusBarElement.classList.remove('visible');
 
        // Remove the element after animation completes
        setTimeout(() => {
          if (this.statusBarElement) {
            this.statusBarElement.innerHTML = '';
            this.statusBarElement.className = 'status-bar';
          }
        }, 300); // Should match CSS transition duration
 
        this.logger.debug('Status bar cleared with animation');
      }
    } catch (error) {
      this.errorManager.handleError(error, {
        component: 'UIManager',
        operation: 'clearStatusBar',
        severity: 'warning',
        context: {
          options,
          errorMessage: error.message
        }
      });
 
      // Fallback to direct DOM manipulation if possible
      try {
        if (this.statusBarElement) {
          this.statusBarElement.innerHTML = '';
          this.statusBarElement.className = 'status-bar';
        }
      } catch (e) {
        console.error('Failed to clear status bar:', e);
      }
    }
  }
 
  /**
   * Show a success message
   * @param {string} message - The success message to display
   * @param {Object} [details] - Additional details to log
   */
  showSuccess(message) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.showStatusBar(message, 'success');
    this.logger.info('Success message shown', {
      message,
      ...details
    });
  }
 
  /**
   * Show a warning message
   * @param {string} message - The warning message to display
   * @param {Object} [details] - Additional details to log
   */
  showWarning(message) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.showStatusBar(message, 'warning');
    this.logger.warn('Warning message shown', {
      message,
      ...details
    });
  }
 
  /**
   * Show an info message
   * @param {string} message - The info message to display
   * @param {Object} [details] - Additional details to log
   */
  showInfo(message) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.showStatusBar(message, 'info');
  }
  /**
   * Show an error message to the user
   * @param {string|Error} error - Error title, message, or Error object
   * @param {string|Object} [details] - Additional error details or options object
   * @param {Object} [options] - Additional options
   * @param {string} [options.errorId] - Unique error ID for tracking
   * @param {Object} [options.context] - Additional context for the error
   * @param {boolean} [options.reportToServer=true] - Whether to report the error to the server
   * @param {string} [options.operation] - The operation that failed
   * @param {string} [options.component] - The component where the error occurred
   */
  showError(error) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    // Handle different parameter patterns
    let errorMessage, errorObj, errorContext;
    if (error instanceof Error) {
      // First parameter is an Error object
      errorObj = error;
      errorMessage = error.message;
      errorContext = typeof details === 'object' && details !== null ? details : {};
    } else if (typeof error === 'string' && details instanceof Error) {
      // First is title, second is Error object
      errorObj = details;
      errorMessage = `${error}: ${details.message}`;
      errorContext = {};
    } else if (typeof error === 'string' && typeof details === 'string') {
      // Both are strings (title and message)
      errorMessage = `${error}: ${details}`;
      errorObj = new Error(errorMessage);
      errorObj.name = error;
      errorContext = {};
    } else if (typeof error === 'string') {
      // First is message, second is options
      errorMessage = error;
      errorObj = new Error(errorMessage);
      errorContext = typeof details === 'object' && details !== null ? details : {};
    } else {
      // Invalid parameters
      const invalidError = new Error('Invalid parameters passed to showError');
      this.errorManager.handleError(invalidError, {
        component: 'UIManager',
        operation: 'showError',
        severity: 'error',
        context: {
          error,
          details,
          options
        }
      });
      return;
    }
 
    // Merge contexts
    const mergedContext = {
      ...errorContext,
      ...options.context
    };
 
    // Report the error through the error manager
    if (options.reportToServer !== false) {
      this.errorManager.handleError(errorObj, {
        component: options.component || 'UIManager',
        operation: options.operation || 'showError',
        severity: 'error',
        context: mergedContext
      });
    }
 
    // Show the error in the UI
    this.showStatusBar(errorMessage, 'error', {
      autoDismiss: false,
      errorId: options.errorId,
      context: mergedContext,
      ...options
    });
 
    // Log the error with additional context
    this.logger.error('Error message shown', {
      error: errorMessage,
      name: errorObj.name,
      stack: errorObj.stack,
      ...mergedContext
    });
  }
  catch(error) {
    // If there's an error in the error handler, log to console
    console.error('Error in showError:', error);
 
    // Try to show a basic error message
    try {
      const fallbackMessage = 'An error occurred';
      this.showStatusBar(fallbackMessage, 'error', {
        autoDismiss: false,
        context: {
          originalError: error instanceof Error ? error.message : String(error),
          timestamp: new Date().toISOString()
        }
      });
    } catch (e) {
      // If we can't even show the error message, just give up
      console.error('Completely failed to show error:', e);
    }
  }
 
  /**
   * Hide loading indicator dand optionally show success message
   * @param {string} successMessage - Optional success message to show after hiding loading
   */
  hideLoading() {
    let successMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    this.clearStatusBar();
    if (successMessage) {
      this.showSuccess(successMessage);
    }
    this.logger.debug('Loading indicator hidden');
  }
 
  /**
   * Update progress bar with current and total values
   * @param {number} current - Current progress value
   * @param {number} total - Total progress value
   * @param {string} message - Progress message
   */
  updateProgress(current, total) {
    let message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
    console.log('🔍 [UI MANAGER DEBUG] updateProgress() called with:', {
      current,
      total,
      message
    });
    if (!this.progressContainer) {
      console.error('🔍 [UI MANAGER DEBUG] Progress container not found in updateProgress');
      this.logger.warn('Progress container not found');
      return;
    }
    console.log('🔍 [UI MANAGER DEBUG] Progress container found, calculating percentage...');
    const percentage = total > 0 ? Math.round(current / total * 100) : 0;
    console.log('🔍 [UI MANAGER DEBUG] Calculated percentage:', percentage);
 
    // Update progress bar
    const progressBar = this.progressContainer.querySelector('.progress-bar-fill');
    console.log('🔍 [UI MANAGER DEBUG] Progress bar element:', progressBar);
    if (progressBar) {
      progressBar.style.width = `${percentage}%`;
      console.log('🔍 [UI MANAGER DEBUG] Progress bar updated to:', `${percentage}%`);
    } else {
      console.error('🔍 [UI MANAGER DEBUG] Progress bar element not found');
    }
 
    // Update percentage text
    const percentageElement = this.progressContainer.querySelector('.progress-percentage');
    console.log('🔍 [UI MANAGER DEBUG] Percentage element:', percentageElement);
    if (percentageElement) {
      percentageElement.textContent = `${percentage}%`;
      console.log('🔍 [UI MANAGER DEBUG] Percentage text updated to:', `${percentage}%`);
    } else {
      console.error('🔍 [UI MANAGER DEBUG] Percentage element not found');
    }
 
    // Update progress text
    const progressText = this.progressContainer.querySelector('.progress-text');
    console.log('🔍 [UI MANAGER DEBUG] Progress text element:', progressText);
    if (progressText && message) {
      progressText.textContent = message;
      console.log('🔍 [UI MANAGER DEBUG] Progress text updated to:', message);
    } else {
      console.error('🔍 [UI MANAGER DEBUG] Progress text element not found or no message');
    }
    this.logger.debug('Progress updated', {
      current,
      total,
      percentage,
      message
    });
    console.log('🔍 [UI MANAGER DEBUG] updateProgress() completed');
  }
 
  /**
   * Update token status display
   * @param {string} status - Token status (valid, expired, etc.)
   * @param {string} message - Status message
   */
  updateTokenStatus(status) {
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    if (!this.tokenStatusElement) {
      this.logger.warn('Token status element not found');
      return;
    }
    this.tokenStatusElement.className = `token-status ${status}`;
    this.tokenStatusElement.textContent = message || status;
    this.logger.debug('Token status updated', {
      status,
      message
    });
  }
 
  /**
   * Update connection status display
   * @param {string} status - Connection status (connected, disconnected, etc.)
   * @param {string} message - Status message
   */
  updateConnectionStatus(status) {
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    if (!this.connectionStatusElement) {
      this.logger.warn('Connection status element not found');
      return;
    }
    this.connectionStatusElement.className = `connection-status ${status}`;
    this.connectionStatusElement.textContent = message || status;
    this.logger.debug('Connection status updated', {
      status,
      message
    });
  }
 
  /**
   * Show current token status with detailed information
   * @param {Object} tokenInfo - Token information object
   */
  showCurrentTokenStatus(tokenInfo) {
    if (!tokenInfo) {
      this.logger.warn('No token info provided');
      return;
    }
    const {
      isValid,
      expiresAt,
      timeRemaining
    } = tokenInfo;
    if (!isValid) {
      this.updateTokenStatus('expired', '');
      return;
    }
    const timeRemainingText = timeRemaining ? ` (${timeRemaining})` : '';
    this.updateTokenStatus('valid', `Token valid${timeRemainingText}`);
    this.logger.info('Current token status displayed', {
      isValid,
      expiresAt,
      timeRemaining
    });
  }
 
  /**
   * Update universal token status bar
   * @param {Object} tokenInfo - Token information object
   */
  updateUniversalTokenStatus(tokenInfo) {
    // Redirect to token-status-indicator instead of universal-token-status
    const tokenStatusBar = document.getElementById('token-status-indicator');
    if (!tokenStatusBar) {
      this.logger.warn('Token status indicator not found');
      return;
    }
    if (!tokenInfo) {
      tokenStatusBar.style.display = 'none';
      return;
    }
    const {
      isValid,
      expiresAt,
      timeRemaining
    } = tokenInfo;
    const statusContent = tokenStatusBar.querySelector('.token-status-content');
    if (statusContent) {
      const icon = statusContent.querySelector('.token-status-icon');
      const text = statusContent.querySelector('.token-status-text');
      const time = statusContent.querySelector('.token-status-time');
      if (isValid) {
        icon.textContent = '✅';
        text.textContent = 'Token valid';
        time.textContent = timeRemaining || '';
      } else {
        icon.textContent = '❌';
        text.textContent = '';
        text.style.visibility = 'hidden';
        time.textContent = '';
      }
    }
    tokenStatusBar.style.display = 'block';
    this.logger.debug('Token status indicator updated', {
      isValid,
      timeRemaining
    });
  }
 
  /**
   * Update home page token status
   * @param {boolean} isLoading - Whether to show loading state
   * @param {string} message - Status message
   */
  updateHomeTokenStatus() {
    let isLoading = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    const homeTokenStatus = document.getElementById('home-token-status');
    if (!homeTokenStatus) {
      console.log('❌ home-token-status element not found!');
      return;
    }
    console.log('✅ Found home-token-status element:', homeTokenStatus);
 
    // Check current token status to determine button color
    let hasValidToken = false;
    let buttonClass = 'btn-danger'; // Default to red
    let buttonText = 'Get New Token';
    try {
      // First check for stashed token in localStorage
      hasValidToken = this.checkForStashedToken();
 
      // If no stashed token, check PingOne client
      if (!hasValidToken && window.app && window.app.pingOneClient) {
        const tokenInfo = window.app.pingOneClient.getCurrentTokenTimeRemaining();
        if (tokenInfo && tokenInfo.token && !tokenInfo.isExpired) {
          hasValidToken = true;
        }
      }
 
      // Set button appearance based on token status
      if (hasValidToken) {
        buttonClass = 'btn-success'; // Green when token is valid
        buttonText = 'Token Valid';
      }
    } catch (error) {
      console.log('Error checking token status:', error);
    }
 
    // Move to bottom of sidebar
    const sidebar = document.querySelector('.sidebar');
    if (sidebar && homeTokenStatus.parentNode !== sidebar) {
      sidebar.appendChild(homeTokenStatus);
      console.log('✅ Moved home-token-status to bottom of sidebar');
    }
 
    // Add debug label to home-token-status container (red, above box)
    if (!document.getElementById('debug-home-token-status-label')) {
      const debugLabel = document.createElement('div');
      debugLabel.id = 'debug-home-token-status-label';
      debugLabel.style.cssText = `
                position: absolute !important;
                top: -30px !important;
                left: 0 !important;
                background: #ff0000 !important;
                color: #ffffff !important;
                padding: 4px 8px !important;
                font-size: 12px !important;
                font-weight: bold !important;
                border: 2px solid #000 !important;
                z-index: 9999 !important;
                white-space: nowrap !important;
                pointer-events: none !important;
            `;
      debugLabel.textContent = 'DEBUG: home-token-status CONTAINER';
 
      // Ensure container has relative positioning
      homeTokenStatus.style.cssText = `
                position: relative !important;
                background: #ffffcc !important;
                border: 1px solid #dee2e6 !important;
                border-radius: 6px !important;
                padding: 2px !important;
                width: fit-content !important;
                height: auto !important;
                display: block !important;
                overflow: visible !important;
                margin-top: auto !important;
            `;
      homeTokenStatus.appendChild(debugLabel);
      console.log('✅ Added debug label to home-token-status container');
    }
    if (isLoading) {
      homeTokenStatus.innerHTML = '';
    } else {
      // Use the provided token-status-indicator markup with dynamic button color and enhanced styling
      homeTokenStatus.innerHTML = `
                <div id="token-status-indicator" class="token-status-indicator valid" role="status" aria-live="polite" style="display: block !important; padding: 0 !important; margin: 0 !important; background: none !important; border: none !important;">
                    <button id="get-token-btn" class="btn ${buttonClass}" style="font-size: 14px !important; padding: 8px 16px !important; margin: 0 !important; font-weight: 500 !important; border-radius: 6px !important; box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important; transition: all 0.2s ease !important;">
                        <i class="fas fa-key"></i> ${buttonText}
                    </button>
                </div>
            `;
      // Wire up the button to call getNewToken if available
      const getTokenBtn = document.getElementById('get-token-btn');
      if (getTokenBtn) {
        getTokenBtn.addEventListener('click', () => {
          if (window.tokenStatusIndicator && typeof window.tokenStatusIndicator.getNewToken === 'function') {
            window.tokenStatusIndicator.getNewToken();
          } else if (typeof this.getNewToken === 'function') {
            this.getNewToken();
          } else {
            // TODO: Refactor: Use Notification or Modal from UI subsystem instead of alert.
            // alert('Get New Token functionality is not available.');
          }
        });
      }
    }
    homeTokenStatus.style.display = 'block';
    this.logger.debug('Home token status updated', {
      isLoading,
      message,
      hasValidToken,
      buttonClass
    });
  }
 
  /**
   * Check for stashed token in localStorage
   * @returns {boolean} True if valid token is found
   */
  checkForStashedToken() {
    try {
      if (typeof localStorage === 'undefined') {
        return false;
      }
      const token = localStorage.getItem('pingone_worker_token');
      const expiry = localStorage.getItem('pingone_token_expiry');
      if (!token || !expiry) {
        return false;
      }
      const expiryTime = parseInt(expiry, 10);
      const now = Date.now();
 
      // Check if token is expired (with 5 minute buffer)
      if (isNaN(expiryTime) || now >= expiryTime - 5 * 60 * 1000) {
        return false;
      }
      return true;
    } catch (error) {
      console.error('Error checking for stashed token:', error);
      return false;
    }
  }
 
  /**
   * Update settings save status with message and type
   * @param {string} message - Status message
   * @param {string} type - Message type (success, error, warning, info)
   */
  updateSettingsSaveStatus(message) {
    let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
    const settingsStatus = document.querySelector('.settings-save-status');
    if (!settingsStatus) {
      this.logger.warn('Settings save status element not found');
      return;
    }
 
    // Update classes
    settingsStatus.className = `settings-save-status ${type} show`;
 
    // Create simple HTML structure with text on the left, icon on the right
    const iconClass = this.getStatusIcon(type);
    settingsStatus.innerHTML = `
            <span>${message}</span>
            <i class="fas ${iconClass}"></i>
        `;
 
    // Auto-hide success messages after 3 seconds
    if (type === 'success') {
      setTimeout(() => {
        settingsStatus.classList.remove('show');
      }, 3000);
    }
    this.logger.info('Settings save status updated', {
      message,
      type
    });
  }
 
  /**
   * Show settings action status with enhanced options
   * @param {string} message - Status message
   * @param {string} type - Message type (success, error, warning, info)
   * @param {Object} options - Additional display options
   * @param {boolean} options.autoDismiss - Whether to auto-dismiss
   * @param {number} options.duration - Duration before auto-dismiss
   */
  showSettingsActionStatus(message) {
    let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const settingsActionStatus = document.getElementById('settings-action-status');
    if (!settingsActionStatus) {
      this.logger.warn('Settings action status element not found');
      return;
    }
 
    // Clear existing content
    settingsActionStatus.innerHTML = '';
    settingsActionStatus.className = `settings-action-status ${type}`;
 
    // Create status content
    const statusContent = document.createElement('div');
    statusContent.className = 'status-content';
    const text = document.createElement('span');
    text.textContent = message;
    statusContent.appendChild(text);
    const icon = document.createElement('i');
    icon.className = `fas ${this.getStatusIcon(type)}`;
    statusContent.appendChild(icon);
    settingsActionStatus.appendChild(statusContent);
    settingsActionStatus.style.display = 'block';
 
    // No auto-dismiss for any type
    this.logger.info('Settings action status shown', {
      message,
      type,
      autoDismiss: false
    });
  }
 
  /**
   * Get appropriate icon class for status type
   * @param {string} type - Status type
   * @returns {string} Icon class name
   */
  getStatusIcon(type) {
    const icons = {
      success: 'fa-check-circle',
      error: 'fa-times-circle',
      warning: 'fa-exclamation-triangle',
      info: 'fa-info-circle'
    };
    return icons[type] || icons.info;
  }
 
  /**
   * Hide settings action status
   */
  hideSettingsActionStatus() {
    const settingsActionStatus = document.getElementById('settings-action-status');
    if (settingsActionStatus) {
      settingsActionStatus.style.display = 'none';
      this.logger.debug('Settings action status hidden');
    }
  }
 
  /**
   * Show import status with operation details
   * @param {string} status - Import status
   * @param {string} message - Status message
   * @param {Object} details - Additional details
   */
  showImportStatus(status) {
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    let details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const importStatus = document.getElementById('import-status');
    if (!importStatus) {
      this.logger.warn('Import status element not found');
      return;
    }
    importStatus.style.display = 'block';
    importStatus.className = `import-status ${status}`;
    const statusText = importStatus.querySelector('.status-text');
    if (statusText) {
      statusText.textContent = message || status;
    }
    this.logger.info('Import status shown', {
      status,
      message,
      details
    });
  }
 
  /**
   * Clear all notifications from the UI
   */
  clearNotifications() {
    if (this.notificationContainer) {
      this.notificationContainer.innerHTML = '';
      this.logger.debug('All notifications cleared');
    }
    this.clearStatusBar();
  }
 
  /**
   * Hide progress display
   */
  hideProgress() {
    if (this.progressContainer) {
      this.progressContainer.style.display = 'none';
      this.logger.debug('Progress display hidden');
    }
  }
 
  /**
   * Show progress section with enhanced debugging and fallback mechanisms
   */
  showProgress() {
    console.log('🔍 [UI MANAGER DEBUG] showProgress() called');
    console.log('🔍 [UI MANAGER DEBUG] this.progressContainer:', this.progressContainer);
 
    // Try multiple ways to get the progress container
    let progressContainer = this.progressContainer;
    if (!progressContainer) {
      console.log('🔍 [UI MANAGER DEBUG] Progress container not found in UI manager, trying direct access...');
      progressContainer = document.getElementById('progress-container');
    }
    if (!progressContainer) {
      console.log('🔍 [UI MANAGER DEBUG] Progress container not found by ID, trying ElementRegistry...');
      if (typeof _elementRegistry.ElementRegistry !== 'undefined' && _elementRegistry.ElementRegistry.progressContainer) {
        progressContainer = _elementRegistry.ElementRegistry.progressContainer();
      }
    }
    if (!progressContainer) {
      console.log('🔍 [UI MANAGER DEBUG] Progress container not found by ElementRegistry, trying class selector...');
      progressContainer = document.querySelector('.progress-container');
    }
    if (!progressContainer) {
      console.error('🔍 [UI MANAGER DEBUG] Progress container not found by any method');
      console.error('🔍 [UI MANAGER DEBUG] Available containers with "progress" in ID:', Array.from(document.querySelectorAll('[id*="progress"]')).map(el => el.id));
      console.error('🔍 [UI MANAGER DEBUG] Available containers with "progress" in class:', Array.from(document.querySelectorAll('[class*="progress"]')).map(el => ({
        id: el.id,
        className: el.className
      })));
      return;
    }
    console.log('🔍 [UI MANAGER DEBUG] Progress container found, showing...');
    console.log('🔍 [UI MANAGER DEBUG] Current display style:', progressContainer.style.display);
    console.log('🔍 [UI MANAGER DEBUG] Current visibility:', progressContainer.offsetParent !== null ? 'visible' : 'hidden');
 
    // Force show the progress container
    progressContainer.style.display = 'block';
    progressContainer.style.visibility = 'visible';
    progressContainer.style.opacity = '1';
 
    // Ensure it's not hidden by CSS
    progressContainer.classList.remove('hidden', 'd-none');
    progressContainer.classList.add('visible');
 
    // Force layout recalculation
    progressContainer.offsetHeight;
    console.log('🔍 [UI MANAGER DEBUG] Display style after setting to block:', progressContainer.style.display);
    console.log('🔍 [UI MANAGER DEBUG] Container visibility:', progressContainer.offsetParent !== null ? 'visible' : 'hidden');
    console.log('🔍 [UI MANAGER DEBUG] Container dimensions:', {
      offsetWidth: progressContainer.offsetWidth,
      offsetHeight: progressContainer.offsetHeight,
      clientWidth: progressContainer.clientWidth,
      clientHeight: progressContainer.clientHeight
    });
 
    // Scroll into view if needed
    if (progressContainer.offsetParent !== null) {
      progressContainer.scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
    }
 
    // Update UI manager's reference
    this.progressContainer = progressContainer;
    this.logger.debug('Progress display shown');
 
    // Additional verification
    setTimeout(() => {
      const isVisible = progressContainer.offsetParent !== null;
      const rect = progressContainer.getBoundingClientRect();
      console.log('🔍 [UI MANAGER DEBUG] Final verification:', {
        isVisible,
        dimensions: {
          width: rect.width,
          height: rect.height
        },
        display: progressContainer.style.display,
        computedDisplay: window.getComputedStyle(progressContainer).display
      });
    }, 100);
  }
 
  /**
   * Set button loading state
   * @param {string} buttonId - Button element ID
   * @param {boolean} isLoading - Whether to show loading state
   */
  setButtonLoading(buttonId, isLoading) {
    const button = document.getElementById(buttonId);
    if (!button) {
      // Don't log warning for buttons that are intentionally hidden or optional
      if (buttonId === 'get-token-quick') {
        this.logger.debug(`Button with ID '${buttonId}' not found (may be hidden)`);
      } else {
        this.logger.warn(`Button with ID '${buttonId}' not found`);
      }
      return;
    }
    if (isLoading) {
      button.disabled = true;
      button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Loading...';
      button.classList.add('loading');
    } else {
      button.disabled = false;
      button.innerHTML = button.getAttribute('data-original-text') || 'Submit';
      button.classList.remove('loading');
    }
    this.logger.debug('Button loading state updated', {
      buttonId,
      isLoading
    });
  }
 
  /**
   * Update population dropdown fields with available populations
   * @param {Array} populations - Array of population objects
   */
  updatePopulationFields(populations) {
    if (!populations || !Array.isArray(populations)) {
      this.logger.warn('Invalid populations data provided');
      return;
    }
    const populationSelects = document.querySelectorAll('select[id*="population"]');
    populationSelects.forEach(select => {
      // Store current selection
      const currentValue = select.value;
 
      // Clear existing options
      select.innerHTML = '';
 
      // Add default option
      const defaultOption = document.createElement('option');
      defaultOption.value = '';
      defaultOption.textContent = 'Select a population...';
      select.appendChild(defaultOption);
 
      // Add population options
      populations.forEach(population => {
        const option = document.createElement('option');
        option.value = population.id;
        option.textContent = population.name;
        select.appendChild(option);
      });
 
      // Restore selection if it still exists
      if (currentValue && select.querySelector(`option[value="${currentValue}"]`)) {
        select.value = currentValue;
      }
    });
    this.logger.info('Population fields updated', {
      populationCount: populations.length,
      selectCount: populationSelects.length
    });
  }
 
  /**
   * Show notification with enhanced options
   * @param {string} title - Notification title
   * @param {string} message - Notification message
   * @param {string} type - Notification type (success, error, warning, info)
   * @param {Object} options - Additional display options
   * @param {boolean} options.autoDismiss - Whether to auto-dismiss
   * @param {number} options.duration - Duration before auto-dismiss
   */
  showNotification(title, message) {
    let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'info';
    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    if (!this.notificationContainer) {
      this.logger.warn('Notification container not found');
      return;
    }
 
    // Clear existing content
    this.notificationContainer.innerHTML = '';
 
    // Create status header content
    const statusContent = document.createElement('div');
    statusContent.className = 'status-content';
 
    // Add icon
    const icon = document.createElement('i');
    icon.className = `fas ${this.getStatusIcon(type)}`;
    statusContent.appendChild(icon);
 
    // Add text
    const text = document.createElement('span');
    if (title && message) {
      text.textContent = `${title}: ${message}`;
    } else {
      text.textContent = title || message;
    }
    statusContent.appendChild(text);
 
    // Add to container
    this.notificationContainer.appendChild(statusContent);
 
    // Auto-dismiss if specified (but keep persistent for success messages)
    const shouldAutoDismiss = options.autoDismiss !== false && type !== 'error' && type !== 'success';
    if (shouldAutoDismiss) {
      const duration = options.duration || 5000;
      setTimeout(() => {
        if (this.notificationContainer && this.notificationContainer.contains(statusContent)) {
          this.notificationContainer.innerHTML = '';
        }
      }, duration);
    }
    this.logger.info('Status header updated', {
      title,
      message,
      type,
      autoDismiss: shouldAutoDismiss
    });
  }
 
  /**
   * Update import progress with detailed statistics
   * @param {number} current - Current progress value
   * @param {number} total - Total progress value
   * @param {string} message - Progress message
   * @param {Object} counts - Statistics counts
   * @param {number} counts.processed - Number of processed items
   * @param {number} counts.success - Number of successful items
   * @param {number} counts.failed - Number of failed items
   * @param {number} counts.skipped - Number of skipped items
   * @param {string} populationName - Population name
   * @param {string} populationId - Population ID
   */
  updateImportProgress(current, total) {
    let message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
    let counts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    let populationName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
    let populationId = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : '';
    // Update main progress
    this.updateProgress(current, total, message);
 
    // Update statistics if provided
    if (counts && typeof counts === 'object') {
      Object.entries(counts).forEach(_ref => {
        let [key, value] = _ref;
        const statElement = document.querySelector(`.stat-value.${key}`);
        if (statElement) {
          statElement.textContent = value || 0;
        }
      });
    }
 
    // Update population information if provided
    if (populationName || populationId) {
      const populationElement = document.querySelector('.detail-value.population-info');
      if (populationElement) {
        populationElement.textContent = populationName || populationId || 'Unknown';
      }
    }
    this.logger.debug('Import progress updated', {
      current,
      total,
      message,
      counts,
      populationName,
      populationId
    });
  }
 
  /**
   * Start import operation with progress tracking
   * @param {Object} options - Operation options
   * @param {string} options.operationType - Type of operation
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   * @param {string} options.populationId - Population ID
   */
  startImportOperation() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    console.log('🔍 [UI MANAGER DEBUG] startImportOperation() called with options:', options);
    const {
      operationType,
      totalUsers,
      populationName,
      populationId
    } = options;
    console.log('🔍 [UI MANAGER DEBUG] About to call showProgress()...');
    this.showProgress();
    console.log('🔍 [UI MANAGER DEBUG] showProgress() completed');
    console.log('🔍 [UI MANAGER DEBUG] About to call updateProgress()...');
    this.updateProgress(0, totalUsers || 0, 'Starting import operation...');
    console.log('🔍 [UI MANAGER DEBUG] updateProgress() completed');
 
    // Update operation details
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    console.log('🔍 [UI MANAGER DEBUG] Operation type element:', operationTypeElement);
    if (operationTypeElement) {
      operationTypeElement.textContent = operationType || 'Import';
      console.log('🔍 [UI MANAGER DEBUG] Operation type updated to:', operationType || 'Import');
    } else {
      console.error('🔍 [UI MANAGER DEBUG] Operation type element not found');
    }
    this.logger.info('Import operation started', {
      operationType,
      totalUsers,
      populationName,
      populationId
    });
    console.log('🔍 [UI MANAGER DEBUG] startImportOperation() completed');
  }
 
  /**
   * Update import operation with session ID
   * @param {string} sessionId - Session ID for tracking
   */
  updateImportOperationWithSessionId(sessionId) {
    if (!sessionId) {
      this.logger.warn('No session ID provided for import operation');
      return;
    }
    const sessionElement = document.querySelector('.detail-value.session-id');
    if (sessionElement) {
      sessionElement.textContent = sessionId;
    }
    this.logger.info('Import operation session ID updated', {
      sessionId
    });
  }
 
  /**
   * Start export operation with progress tracking
   * @param {Object} options - Operation options
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   */
  startExportOperation() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      totalUsers,
      populationName
    } = options;
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Starting export operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Export';
    }
    this.logger.info('Export operation started', {
      totalUsers,
      populationName
    });
  }
 
  /**
   * Start delete operation with progress tracking
   * @param {Object} options - Operation options
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   */
  startDeleteOperation() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      totalUsers,
      populationName
    } = options;
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Starting delete operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Delete';
    }
    this.logger.info('Delete operation started', {
      totalUsers,
      populationName
    });
  }
 
  /**
   * Start modify operation with progress tracking
   * @param {Object} options - Operation options
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   */
  startModifyOperation() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      totalUsers,
      populationName
    } = options;
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Starting modify operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Modify';
    }
    this.logger.info('Modify operation started', {
      totalUsers,
      populationName
    });
  }
 
  /**
   * Complete operation with results
   * @param {Object} results - Operation results
   * @param {number} results.processed - Number of processed items
   * @param {number} results.success - Number of successful items
   * @param {number} results.failed - Number of failed items
   * @param {number} results.skipped - Number of skipped items
   */
  completeOperation() {
    let results = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      processed,
      success,
      failed,
      skipped
    } = results;
    this.updateProgress(processed || 0, processed || 0, 'Operation completed');
 
    // Show completion message
    const message = `Operation completed: ${success || 0} successful, ${failed || 0} failed, ${skipped || 0} skipped`;
    this.showSuccess(message);
 
    // Hide progress after delay
    setTimeout(() => {
      this.hideProgress();
    }, 2000);
    this.logger.info('Operation completed', {
      processed,
      success,
      failed,
      skipped
    });
  }
 
  /**
   * Handle duplicate users with decision callback
   * @param {Array} duplicates - Array of duplicate user objects
   * @param {Function} onDecision - Callback function for user decision
   */
  handleDuplicateUsers(duplicates, onDecision) {
    if (!duplicates || duplicates.length === 0) {
      this.logger.warn('No duplicates provided for handling');
      return;
    }
    const message = `Found ${duplicates.length} duplicate users. How would you like to proceed?`;
    this.showWarning(message);
 
    // In a real implementation, you would show a modal or dialog here
    // For now, we'll just log the decision
    this.logger.info('Duplicate users found', {
      count: duplicates.length
    });
    if (onDecision && typeof onDecision === 'function') {
      onDecision('skip'); // Default to skip
    }
  }
 
  /**
   * Debug logging for development
   * @param {string} area - Debug area
   * @param {string} message - Debug message
   */
  debugLog(area, message) {
    if (DEBUG_MODE) {
      this.logger.debug(`[${area}] ${message}`);
    }
  }
 
  /**
   * Show status message with type
   * @param {string} type - Message type
   * @param {string} message - Message content
   * @param {string} details - Additional details
   */
  showStatusMessage(type, message) {
    let details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
    const fullMessage = details ? `${message}: ${details}` : message;
    this.showNotification('Status Update', fullMessage, type);
  }
 
  /**
   * Show export status
   */
  showExportStatus() {
    this.showProgress();
    this.updateProgress(0, 100, 'Preparing export...');
    this.logger.info('Export status shown');
  }
 
  /**
   * Update export progress
   * @param {number} current - Current progress
   * @param {number} total - Total progress
   * @param {string} message - Progress message
   * @param {Object} counts - Statistics counts
   */
  updateExportProgress(current, total, message) {
    let counts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    this.updateProgress(current, total, message);
 
    // Update export-specific statistics
    if (counts && typeof counts === 'object') {
      Object.entries(counts).forEach(_ref2 => {
        let [key, value] = _ref2;
        const statElement = document.querySelector(`.stat-value.${key}`);
        if (statElement) {
          statElement.textContent = value || 0;
        }
      });
    }
    this.logger.debug('Export progress updated', {
      current,
      total,
      message,
      counts
    });
  }
 
  /**
   * Show delete status
   * @param {number} totalUsers - Total number of users
   * @param {string} populationName - Population name
   * @param {string} populationId - Population ID
   */
  showDeleteStatus(totalUsers, populationName, populationId) {
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Preparing delete operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Delete';
    }
    this.logger.info('Delete status shown', {
      totalUsers,
      populationName,
      populationId
    });
  }
 
  /**
   * Update delete progress
   * @param {number} current - Current progress
   * @param {number} total - Total progress
   * @param {string} message - Progress message
   * @param {Object} counts - Statistics counts
   * @param {string} populationName - Population name
   * @param {string} populationId - Population ID
   */
  updateDeleteProgress(current, total, message) {
    let counts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    let populationName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
    let populationId = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : '';
    this.updateProgress(current, total, message);
 
    // Update delete-specific statistics
    if (counts && typeof counts === 'object') {
      Object.entries(counts).forEach(_ref3 => {
        let [key, value] = _ref3;
        const statElement = document.querySelector(`.stat-value.${key}`);
        if (statElement) {
          statElement.textContent = value || 0;
        }
      });
    }
    this.logger.debug('Delete progress updated', {
      current,
      total,
      message,
      counts,
      populationName,
      populationId
    });
  }
 
  /**
   * Show modify status
   * @param {number} totalUsers - Total number of users
   */
  showModifyStatus(totalUsers) {
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Preparing modify operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Modify';
    }
    this.logger.info('Modify status shown', {
      totalUsers
    });
  }
 
  /**
   * Update modify progress
   * @param {number} current - Current progress
   * @param {number} total - Total progress
   * @param {string} message - Progress message
   * @param {Object} counts - Statistics counts
   */
  updateModifyProgress(current, total, message) {
    let counts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    this.updateProgress(current, total, message);
 
    // Update modify-specific statistics
    if (counts && typeof counts === 'object') {
      Object.entries(counts).forEach(_ref4 => {
        let [key, value] = _ref4;
        const statElement = document.querySelector(`.stat-value.${key}`);
        if (statElement) {
          statElement.textContent = value || 0;
        }
      });
    }
    this.logger.debug('Modify progress updated', {
      current,
      total,
      message,
      counts
    });
  }
}
 
// Export the UIManager class
exports.UIManager = UIManager;
 
}).call(this)}).call(this,require('_process'))
},{"./circular-progress.js":43,"./element-registry.js":47,"./error/error-types.js":48,"./progress-manager.js":59,"@babel/runtime/helpers/interopRequireDefault":2,"_process":29}],69:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.VersionManager = void 0;
class VersionManager {
  constructor() {
    this.version = '6.1'; // Update this with each new version
    console.log(`Version Manager initialized with version ${this.version}`);
  }
  getVersion() {
    return this.version;
  }
  getFormattedVersion() {
    return `v${this.version}`;
  }
  updateTitle() {
    // Update the main title
    const title = document.querySelector('h1');
    if (title) {
      // Remove any existing version number
      const baseTitle = title.textContent.replace(/\s*\(v\d+\.\d+\.\d+\)\s*$/, '').trim();
      title.textContent = `${baseTitle} (${this.getFormattedVersion()})`;
    }
 
    // Update the document title
    document.title = `PingOne User Import ${this.getFormattedVersion()}`;
 
    // Update the import button text
    this.updateImportButton();
 
    // Update the top version badge
    this.updateTopVersionBadge();
 
    // Add version badge to the sidebar above the Ping Identity logo
    this.addSidebarVersionBadge();
  }
  updateImportButton() {
    const importButton = document.getElementById('start-import-btn');
    if (importButton) {
      const baseText = importButton.textContent.replace(/\s*\(v\d+\.\d+\.\d+\)\s*$/, '').trim();
      importButton.innerHTML = `<i class="pi pi-upload"></i> ${baseText} (${this.getFormattedVersion()})`;
    }
  }
  updateTopVersionBadge() {
    const versionText = document.getElementById('version-text');
    if (versionText) {
      versionText.textContent = this.getFormattedVersion();
    }
  }
  addSidebarVersionBadge() {
    // Remove existing badges if they exist
    const existingTopLeftBadge = document.getElementById('top-left-version-badge');
    if (existingTopLeftBadge) {
      existingTopLeftBadge.remove();
    }
    const existingSidebarBadge = document.getElementById('sidebar-version-badge');
    if (existingSidebarBadge) {
      existingSidebarBadge.remove();
    }
 
    // Check if sidebar version badge already exists
    if (document.getElementById('sidebar-version-badge')) {
      return;
    }
 
    // Create sidebar version badge
    const badge = document.createElement('div');
    badge.id = 'sidebar-version-badge';
    badge.className = 'sidebar-version-badge';
    badge.textContent = this.getFormattedVersion();
 
    // Find the footer and insert the badge in the footer-left section, after the logo and trademark
    const footer = document.querySelector('.ping-footer');
    if (footer) {
      const footerLeft = footer.querySelector('.footer-left');
      if (footerLeft) {
        // Insert the badge after the footer-logo div
        const logoDiv = footerLeft.querySelector('.footer-logo');
        if (logoDiv) {
          // Insert after the logo div
          footerLeft.insertBefore(badge, logoDiv.nextSibling);
        } else {
          // Fallback: insert at the beginning of footer-left
          footerLeft.insertBefore(badge, footerLeft.firstChild);
        }
      } else {
        // Fallback: insert at the end of the footer
        footer.appendChild(badge);
      }
    } else {
      // Fallback: add to body if footer not found
      document.body.appendChild(badge);
    }
  }
}
 
// ES Module export
exports.VersionManager = VersionManager;
 
},{}],70:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.apiLogger = exports.WinstonLogger = void 0;
exports.createComponentLogger = createComponentLogger;
exports.createWinstonLogger = createWinstonLogger;
exports.uiLogger = exports.tokenLogger = exports.settingsLogger = exports.fileLogger = exports.defaultLogger = void 0;
/**
 * @fileoverview Winston-compatible logger for frontend/browser environment
 * 
 * This module provides a Winston-like logging interface for the frontend
 * that maintains consistency with server-side Winston logging while
 * working within browser constraints.
 * 
 * Features:
 * - Winston-compatible API (info, warn, error, debug)
 * - Structured logging with metadata
 * - Timestamp formatting
 * - Log level filtering
 * - Console and server transport support
 * - Error stack trace handling
 * - Environment-aware configuration
 */
 
/**
 * Winston-compatible logger for browser environment
 */
class WinstonLogger {
  constructor() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    this.level = options.level || this.getDefaultLevel();
    this.service = options.service || 'pingone-import-frontend';
    this.environment = options.environment || process.env.NODE_ENV || 'development';
    this.enableServerLogging = options.enableServerLogging !== false;
    this.enableConsoleLogging = options.enableConsoleLogging !== false;
 
    // Log level hierarchy
    this.levels = {
      error: 0,
      warn: 1,
      info: 2,
      debug: 3
    };
 
    // Initialize transports
    this.transports = [];
    this.initializeTransports();
  }
 
  /**
   * Get default log level based on environment
   */
  getDefaultLevel() {
    if (this.environment === 'production') {
      return 'info';
    } else if (this.environment === 'test') {
      return 'warn';
    } else {
      return 'debug';
    }
  }
 
  /**
   * Initialize logging transports
   */
  initializeTransports() {
    // Console transport
    if (this.enableConsoleLogging) {
      this.transports.push({
        name: 'console',
        log: (level, message, meta) => this.logToConsole(level, message, meta)
      });
    }
 
    // Server transport (if enabled)
    if (this.enableServerLogging) {
      this.transports.push({
        name: 'server',
        log: (level, message, meta) => this.logToServer(level, message, meta)
      });
    }
  }
 
  /**
   * Check if a log level should be logged
   */
  shouldLog(level) {
    return this.levels[level] <= this.levels[this.level];
  }
 
  /**
   * Format timestamp
   */
  formatTimestamp() {
    return new Date().toISOString();
  }
 
  /**
   * Format log entry
   */
  formatLogEntry(level, message) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const timestamp = this.formatTimestamp();
    return {
      timestamp,
      level,
      message,
      service: this.service,
      environment: this.environment,
      ...meta
    };
  }
 
  /**
   * Log to console with Winston-like formatting
   */
  logToConsole(level, message) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    if (!this.shouldLog(level)) return;
    const logEntry = this.formatLogEntry(level, message, meta);
    const timestamp = logEntry.timestamp;
    const levelUpper = level.toUpperCase();
 
    // Create formatted console message
    let consoleMessage = `[${timestamp}] [${this.service}] ${levelUpper}: ${message}`;
 
    // Add metadata if present
    if (Object.keys(meta).length > 0) {
      consoleMessage += `\n${JSON.stringify(meta, null, 2)}`;
    }
 
    // Use appropriate console method
    switch (level) {
      case 'error':
        console.error(consoleMessage);
        break;
      case 'warn':
        console.warn(consoleMessage);
        break;
      case 'info':
        console.info(consoleMessage);
        break;
      case 'debug':
        console.debug(consoleMessage);
        break;
      default:
        console.log(consoleMessage);
    }
  }
 
  /**
   * Log to server via API endpoint
   */
  async logToServer(level, message) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    if (!this.shouldLog(level)) return;
    try {
      // Format the request body according to the API expectations
      const requestBody = {
        message,
        level,
        data: meta,
        source: 'frontend'
      };
 
      // Send to server logging endpoint
      await fetch('/api/logs/ui', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      });
    } catch (error) {
      // Handle connection refused errors silently during startup
      if (error.message.includes('Failed to fetch') || error.message.includes('ERR_CONNECTION_REFUSED')) {
        // Don't log connection refused errors to avoid console spam during startup
        return;
      }
      // Fallback to console if server logging fails
      console.warn('Server logging failed, falling back to console:', error.message);
      this.logToConsole(level, message, meta);
    }
  }
 
  /**
   * Main logging method
   */
  log(level, message) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    if (!this.shouldLog(level)) return;
 
    // Send to all transports
    this.transports.forEach(transport => {
      try {
        transport.log(level, message, meta);
      } catch (error) {
        console.error(`Error in ${transport.name} transport:`, error);
      }
    });
  }
 
  /**
   * Log info level message
   */
  info(message) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('info', message, meta);
  }
 
  /**
   * Log warn level message
   */
  warn(message) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('warn', message, meta);
  }
 
  /**
   * Log error level message
   */
  error(message) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('error', message, meta);
  }
 
  /**
   * Log debug level message
   */
  debug(message) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('debug', message, meta);
  }
 
  /**
   * Log error with stack trace
   */
  errorWithStack(message, error) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const errorMeta = {
      ...meta,
      error: {
        message: error.message,
        stack: error.stack,
        code: error.code,
        name: error.name
      }
    };
    this.error(message, errorMeta);
  }
 
  /**
   * Create child logger with additional metadata
   */
  child() {
    var _this = this;
    let additionalMeta = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const childLogger = new WinstonLogger({
      level: this.level,
      service: this.service,
      environment: this.environment,
      enableServerLogging: this.enableServerLogging,
      enableConsoleLogging: this.enableConsoleLogging
    });
 
    // Override formatLogEntry to include additional metadata
    childLogger.formatLogEntry = function (level, message) {
      let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      const baseEntry = _this.formatLogEntry(level, message, meta);
      return {
        ...baseEntry,
        ...additionalMeta
      };
    };
    return childLogger;
  }
 
  /**
   * Set log level
   */
  setLevel(level) {
    if (this.levels.hasOwnProperty(level)) {
      this.level = level;
    } else {
      this.warn(`Invalid log level: ${level}`);
    }
  }
 
  /**
   * Enable/disable server logging
   */
  setServerLogging(enabled) {
    this.enableServerLogging = enabled;
 
    // Update transports
    this.transports = this.transports.filter(t => t.name !== 'server');
    if (enabled) {
      this.transports.push({
        name: 'server',
        log: (level, message, meta) => this.logToServer(level, message, meta)
      });
    }
  }
 
  /**
   * Enable/disable console logging
   */
  setConsoleLogging(enabled) {
    this.enableConsoleLogging = enabled;
 
    // Update transports
    this.transports = this.transports.filter(t => t.name !== 'console');
    if (enabled) {
      this.transports.push({
        name: 'console',
        log: (level, message, meta) => this.logToConsole(level, message, meta)
      });
    }
  }
}
 
/**
 * Create default logger instance
 */
exports.WinstonLogger = WinstonLogger;
function createWinstonLogger() {
  let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return new WinstonLogger(options);
}
 
/**
 * Create component-specific logger
 */
function createComponentLogger(component) {
  let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return createWinstonLogger({
    ...options,
    service: `${options.service || 'pingone-import'}-${component}`
  });
}
 
/**
 * Default logger instances
 */
const defaultLogger = exports.defaultLogger = createWinstonLogger();
const apiLogger = exports.apiLogger = createComponentLogger('api');
const uiLogger = exports.uiLogger = createComponentLogger('ui');
const fileLogger = exports.fileLogger = createComponentLogger('file');
const settingsLogger = exports.settingsLogger = createComponentLogger('settings');
const tokenLogger = exports.tokenLogger = createComponentLogger('token');
 
// Export the class for custom instances
 
}).call(this)}).call(this,require('_process'))
},{"_process":29}],71:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CentralizedLogger = void 0;
/**
 * Centralized Logger Utility
 * 
 * Provides structured logging with sensitive data masking, remote logging,
 * and consistent formatting across the application.
 */
 
class CentralizedLogger {
  constructor() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    this.component = options.component || 'app';
    this.level = options.level || 'info';
    this.enableRemoteLogging = options.enableRemoteLogging !== false;
    this.enableConsoleLogging = options.enableConsoleLogging !== false;
    this.sensitivePatterns = [/password/i, /token/i, /secret/i, /key/i, /credential/i, /auth/i];
  }
 
  /**
   * Mask sensitive data in log messages
   */
  maskSensitiveData(data) {
    if (typeof data === 'string') {
      return data.replace(/("(?:password|token|secret|key|credential|auth)"\s*:\s*")([^"]+)"/gi, '$1***MASKED***"');
    }
    if (typeof data === 'object' && data !== null) {
      const masked = {
        ...data
      };
      for (const key in masked) {
        if (this.sensitivePatterns.some(pattern => pattern.test(key))) {
          masked[key] = '***MASKED***';
        } else if (typeof masked[key] === 'object') {
          masked[key] = this.maskSensitiveData(masked[key]);
        }
      }
      return masked;
    }
    return data;
  }
 
  /**
   * Format log message with timestamp and component info
   */
  formatMessage(level, message) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    const timestamp = new Date().toISOString();
    const component = this.component;
    let formattedMessage = `[${timestamp}] [${level.toUpperCase()}] [${component}] ${message}`;
    if (data) {
      const maskedData = this.maskSensitiveData(data);
      formattedMessage += ` | Data: ${JSON.stringify(maskedData, null, 2)}`;
    }
    return formattedMessage;
  }
 
  /**
   * Send log to remote endpoint
   */
  async sendRemoteLog(level, message) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    if (!this.enableRemoteLogging) return;
    try {
      const logEntry = {
        timestamp: new Date().toISOString(),
        level,
        component: this.component,
        message,
        data: this.maskSensitiveData(data),
        userAgent: navigator.userAgent,
        url: window.location.href
      };
      await fetch('/api/logs', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(logEntry)
      });
    } catch (error) {
      // Fallback to console if remote logging fails
      if (this.enableConsoleLogging) {
        console.warn('Remote logging failed:', error);
      }
    }
  }
 
  /**
   * Log debug message
   */
  debug(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    // Only log if debug mode is enabled in settings
    const settings = window.settings || {};
    if (!settings.debugMode) {
      return; // Suppress debug log if not in debug mode
    }
    const formattedMessage = this.formatMessage('debug', message, data);
    if (this.enableConsoleLogging) {
      console.debug(formattedMessage);
    }
 
    // Optionally, send debug logs remotely if needed for remote debugging sessions
    this.sendRemoteLog('debug', message, data);
  }
 
  /**
   * Log info message
   */
  info(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    const formattedMessage = this.formatMessage('info', message, data);
    if (this.enableConsoleLogging) {
      console.log(formattedMessage);
    }
    this.sendRemoteLog('info', message, data);
  }
 
  /**
   * Log warning message
   */
  warn(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    const formattedMessage = this.formatMessage('warn', message, data);
    if (this.enableConsoleLogging) {
      console.warn(formattedMessage);
    }
    this.sendRemoteLog('warn', message, data);
  }
 
  /**
   * Log error message
   */
  error(message) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    const formattedMessage = this.formatMessage('error', message, data);
    if (this.enableConsoleLogging) {
      console.error(formattedMessage);
    }
    this.sendRemoteLog('error', message, data);
  }
 
  /**
   * Create child logger with additional component context
   */
  child() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const childComponent = options.component ? `${this.component}.${options.component}` : this.component;
    return new CentralizedLogger({
      ...options,
      component: childComponent,
      level: options.level || this.level,
      enableRemoteLogging: options.enableRemoteLogging !== undefined ? options.enableRemoteLogging : this.enableRemoteLogging,
      enableConsoleLogging: options.enableConsoleLogging !== undefined ? options.enableConsoleLogging : this.enableConsoleLogging
    });
  }
}
 
// Export for both ES modules and CommonJS
exports.CentralizedLogger = CentralizedLogger;
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    CentralizedLogger
  };
} else if (typeof window !== 'undefined') {
  window.CentralizedLogger = CentralizedLogger;
}
 
},{}],72:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UI_CONFIG = exports.MESSAGES = exports.BUSINESS_CONFIG = exports.API_CONFIG = void 0;
/**
 * Configuration Constants for PingOne Import Tool
 * Centralizes hardcoded values: timeouts, URLs, selectors, messages
 */
 
// API Configuration
const API_CONFIG = exports.API_CONFIG = {
  ENDPOINTS: {
    SETTINGS: '/api/settings',
    IMPORT: '/api/import',
    EXPORT: '/api/export',
    POPULATIONS: '/api/populations',
    TEST_CONNECTION: '/api/pingone/test-connection',
    LOGS: '/api/logs'
  },
  TIMEOUTS: {
    DEFAULT: 10000,
    LONG_OPERATION: 30000,
    FILE_UPLOAD: 60000,
    CONNECTION_TEST: 5000
  },
  RETRY: {
    MAX_ATTEMPTS: 3,
    DELAYS: [1000, 2000, 5000]
  }
};
 
// UI Configuration
const UI_CONFIG = exports.UI_CONFIG = {
  SELECTORS: {
    APP_CONTAINER: '.app-container',
    NAV_ITEMS: '[data-view]',
    SETTINGS_FORM: '#settings-form',
    PROGRESS_BAR: '.progress-bar',
    STATUS_INDICATOR: '.status-indicator',
    MODAL_BACKDROP: '.modal-backdrop'
  },
  CLASSES: {
    HIDDEN: 'hidden',
    ACTIVE: 'active',
    LOADING: 'loading',
    ERROR: 'error',
    SUCCESS: 'success'
  }
};
 
// Messages
const MESSAGES = exports.MESSAGES = {
  SUCCESS: {
    SETTINGS_SAVED: 'Settings saved successfully',
    FILE_UPLOADED: 'File uploaded successfully',
    CONNECTION_SUCCESS: 'Connection test successful'
  },
  ERROR: {
    NETWORK_ERROR: 'Network connection error',
    FILE_TOO_LARGE: 'File size exceeds 10MB limit',
    SETTINGS_SAVE_FAILED: 'Failed to save settings',
    CONNECTION_FAILED: 'Connection test failed'
  }
};
 
// Business Config
const BUSINESS_CONFIG = exports.BUSINESS_CONFIG = {
  FILE_UPLOAD: {
    MAX_SIZE: 10 * 1024 * 1024,
    // 10MB
    ALLOWED_TYPES: ['.csv', '.txt']
  },
  IMPORT: {
    BATCH_SIZE: 100,
    MAX_CONCURRENT: 5
  }
};
 
// Make available globally
if (typeof window !== 'undefined') {
  window.API_CONFIG = API_CONFIG;
  window.UI_CONFIG = UI_CONFIG;
  window.MESSAGES = MESSAGES;
  window.BUSINESS_CONFIG = BUSINESS_CONFIG;
}
 
},{}],73:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ErrorHandler = void 0;
/**
 * Standardized Error Handling Utility
 * 
 * Provides consistent error handling patterns, error wrapping for async operations,
 * and standardized error reporting across the application.
 */
 
class ErrorHandler {
  constructor() {
    let logger = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    this.logger = logger || {
      error: (msg, data) => console.error(msg, data),
      warn: (msg, data) => console.warn(msg, data),
      debug: (msg, data) => console.debug(msg, data)
    };
  }
 
  /**
   * Wrap async functions with standardized error handling
   * @param {Function} asyncFn - The async function to wrap
   * @param {string} context - Context description for error reporting
   * @param {Object} options - Options for error handling
   * @returns {Function} Wrapped function with error handling
   */
  wrapAsync(asyncFn) {
    var _this = this;
    let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Unknown operation';
    let userMessage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    const {
      retries = 0,
      retryDelay = 1000,
      fallbackValue = null,
      suppressErrors = false,
      rethrow = false
    } = options;
    return async function () {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      for (let attempt = 0; attempt <= retries; attempt++) {
        try {
          return await asyncFn(...args);
        } catch (error) {
          if (attempt < retries) {
            _this.logger.warn(`${context} failed (attempt ${attempt + 1}/${retries + 1}), retrying...`, {
              error: error.message,
              args: _this._sanitizeArgs(args)
            });
            await _this._delay(retryDelay * (attempt + 1));
            continue;
          }
 
          // Final attempt failed
          _this.handleError(error, context, {
            userMessage: userMessage || 'An unexpected error occurred.',
            retries,
            suppress: suppressErrors
          });
          if (rethrow) {
            throw error;
          }
          return fallbackValue;
        }
      }
      return fallbackValue; // Should be unreachable if rethrow is false
    };
  }
 
  /**
   * Wrap synchronous functions with standardized error handling
   * @param {Function} syncFn - The synchronous function to wrap
   * @param {string} context - Context description for error reporting
   * @param {Object} options - Options for error handling
   * @returns {Function} Wrapped function with error handling
   */
  wrapSync(syncFn) {
    var _this2 = this;
    let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Unknown operation';
    let userMessage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    const {
      fallbackValue = null,
      suppressErrors = false,
      rethrow = false
    } = options;
    return function () {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      try {
        return syncFn(...args);
      } catch (error) {
        _this2.handleError(error, context, {
          userMessage: userMessage || 'An unexpected error occurred.',
          suppress: suppressErrors,
          args: _this2._sanitizeArgs(args)
        });
        if (rethrow) {
          throw error;
        }
        return fallbackValue;
      }
    };
  }
 
  /**
   * Create a standardized error object
   * @param {string} message - Error message
   * @param {string} code - Error code
   * @param {Object} context - Additional context
   * @param {Error} originalError - Original error if wrapping
   * @returns {Error} Standardized error object
   */
  createError(message) {
    let code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'UNKNOWN_ERROR';
    let context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    let originalError = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
    const error = new Error(message);
    error.code = code;
    error.context = context;
    error.timestamp = new Date().toISOString();
    if (originalError) {
      error.originalError = originalError;
      error.originalStack = originalError.stack;
    }
    return error;
  }
 
  /**
   * Handle and report errors with context
   * @param {Error} error - The error to handle
   * @param {string} context - Context description
   * @param {Object} options - Additional data for error reporting
   */
  handleError(error) {
    let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Unknown context';
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const {
      userMessage,
      suppress,
      ...additionalData
    } = options;
    if (suppress) return; // Do not log or show UI error if suppressed
 
    const errorData = {
      message: error.message,
      code: error.code || 'UNHANDLED_EXCEPTION',
      context: context,
      timestamp: new Date().toISOString(),
      stack: error.stack,
      ...additionalData
    };
    this.logger.error(`Error in ${context}:`, errorData);
 
    // Report to external service if configured
    this._reportToErrorService(errorData);
 
    // Show UI notification if UI manager is available
    if (typeof window !== 'undefined' && window.app && window.app.uiManager) {
      const uiManager = window.app.uiManager;
      // Prioritize the user-friendly message for the UI
      const displayMessage = userMessage || error.message;
      uiManager.showError(`Error: ${context}`, displayMessage);
    }
  }
 
  /**
   * Wrap DOM event handlers with error handling
   * @param {Function} handler - The event handler function
   * @param {string} context - Context description
   * @returns {Function} Wrapped event handler
   */
  wrapEventHandler(handler) {
    let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Event handler';
    return event => {
      try {
        return handler(event);
      } catch (error) {
        this.logger.error(`${context} failed`, {
          error: error.message,
          eventType: event?.type,
          target: event?.target?.tagName || 'unknown'
        });
 
        // Prevent error from bubbling up and breaking the UI
        event?.preventDefault?.();
        event?.stopPropagation?.();
      }
    };
  }
 
  /**
   * Create a safe function that never throws
   * @param {Function} fn - Function to make safe
   * @param {string} context - Context description
   * @param {*} fallbackValue - Value to return on error
   * @returns {Function} Safe function
   */
  makeSafe(fn) {
    var _this3 = this;
    let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Safe function';
    let fallbackValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    return function () {
      for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
        args[_key3] = arguments[_key3];
      }
      try {
        return fn(...args);
      } catch (error) {
        _this3.logger.warn(`${context} failed safely`, {
          error: error.message,
          args: _this3._sanitizeArgs(args)
        });
        return fallbackValue;
      }
    };
  }
 
  /**
   * Validate and handle API responses
   * @param {Response} response - Fetch response object
   * @param {string} context - Context description
   * @returns {Promise<Object>} Parsed response data
   */
  async handleApiResponse(response) {
    let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'API call';
    try {
      if (!response.ok) {
        const errorData = {
          status: response.status,
          statusText: response.statusText,
          url: response.url
        };
        let errorMessage = `${context} failed with status ${response.status}`;
        try {
          const errorBody = await response.text();
          errorData.body = errorBody;
 
          // Try to parse as JSON for more details
          try {
            const jsonError = JSON.parse(errorBody);
            if (jsonError.message) {
              errorMessage = jsonError.message;
            }
          } catch (e) {
            // Not JSON, use text as is
          }
        } catch (e) {
          // Could not read response body
        }
        throw this.createError(errorMessage, `HTTP_${response.status}`, errorData);
      }
      const data = await response.json();
      return data;
    } catch (error) {
      if (error.code && error.code.startsWith('HTTP_')) {
        throw error; // Re-throw our custom HTTP errors
      }
 
      // Handle JSON parsing or other errors
      throw this.createError(`${context} response parsing failed`, 'RESPONSE_PARSE_ERROR', {
        originalError: error.message
      });
    }
  }
 
  // Private helper methods
  _sanitizeArgs(args) {
    return args.map(arg => {
      if (typeof arg === 'string' && arg.length > 100) {
        return arg.substring(0, 100) + '...';
      }
      if (typeof arg === 'object' && arg !== null) {
        return {
          ...arg,
          _truncated: true
        };
      }
      return arg;
    });
  }
  _delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
  _reportToErrorService(errorData) {
    // Placeholder for error reporting service integration
    // Could send to external service, local storage, etc.
    if (typeof window !== 'undefined' && window.errorReportingEnabled) {
      // Example: send to error reporting service
      // fetch('/api/errors', { method: 'POST', body: JSON.stringify(errorData) });
    }
  }
}
 
// Export for both ES modules and CommonJS
exports.ErrorHandler = ErrorHandler;
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    ErrorHandler
  };
} else if (typeof window !== 'undefined') {
  window.ErrorHandler = ErrorHandler;
}
 
},{}],74:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SafeDOM = void 0;
/**
 * Safe DOM Utility
 * 
 * Provides safe DOM element selection and manipulation with error handling
 * and null checks to prevent common DOM-related errors.
 */
 
class SafeDOM {
  constructor() {
    let logger = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    this.logger = logger || {
      warn: (msg, data) => console.warn(msg, data),
      error: (msg, data) => console.error(msg, data),
      debug: (msg, data) => console.debug(msg, data)
    };
  }
 
  /**
   * Safely select a single element
   */
  select(selector) {
    let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
    try {
      if (!selector) {
        this.logger.warn('SafeDOM: Empty selector provided');
        return null;
      }
      const element = context.querySelector(selector);
      if (!element) {
        this.logger.debug(`SafeDOM: Element not found for selector: ${selector}`);
      }
      return element;
    } catch (error) {
      this.logger.error('SafeDOM: Error selecting element', {
        selector,
        error: error.message
      });
      return null;
    }
  }
 
  /**
   * Safely select multiple elements
   */
  selectAll(selector) {
    let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
    try {
      if (!selector) {
        this.logger.warn('SafeDOM: Empty selector provided');
        return [];
      }
      const elements = context.querySelectorAll(selector);
      return Array.from(elements);
    } catch (error) {
      this.logger.error('SafeDOM: Error selecting elements', {
        selector,
        error: error.message
      });
      return [];
    }
  }
 
  /**
   * Safely get element by ID
   */
  getElementById(id) {
    try {
      if (!id) {
        this.logger.warn('SafeDOM: Empty ID provided');
        return null;
      }
      const element = document.getElementById(id);
      if (!element) {
        this.logger.debug(`SafeDOM: Element not found for ID: ${id}`);
      }
      return element;
    } catch (error) {
      this.logger.error('SafeDOM: Error getting element by ID', {
        id,
        error: error.message
      });
      return null;
    }
  }
 
  /**
   * Safely set text content
   */
  setText(element, text) {
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to setText');
        return false;
      }
      element.textContent = text || '';
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error setting text content', {
        text,
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Safely set HTML content (with sanitization warning)
   */
  setHTML(element, html) {
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to setHTML');
        return false;
      }
 
      // Warning about potential XSS
      if (html && typeof html === 'string' && (html.includes('<script') || html.includes('javascript:'))) {
        this.logger.warn('SafeDOM: Potentially unsafe HTML detected', {
          html: html.substring(0, 100)
        });
      }
      element.innerHTML = html || '';
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error setting HTML content', {
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Safely add event listener
   */
  addEventListener(element, event, handler) {
    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to addEventListener');
        return false;
      }
      if (typeof handler !== 'function') {
        this.logger.warn('SafeDOM: Non-function handler provided to addEventListener');
        return false;
      }
      element.addEventListener(event, handler, options);
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error adding event listener', {
        event,
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Safely remove event listener
   */
  removeEventListener(element, event, handler) {
    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to removeEventListener');
        return false;
      }
      element.removeEventListener(event, handler, options);
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error removing event listener', {
        event,
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Safely add CSS class
   */
  addClass(element, className) {
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to addClass');
        return false;
      }
      if (!className) {
        this.logger.warn('SafeDOM: Empty className provided to addClass');
        return false;
      }
      element.classList.add(className);
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error adding CSS class', {
        className,
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Safely remove CSS class
   */
  removeClass(element, className) {
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to removeClass');
        return false;
      }
      if (!className) {
        this.logger.warn('SafeDOM: Empty className provided to removeClass');
        return false;
      }
      element.classList.remove(className);
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error removing CSS class', {
        className,
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Safely toggle CSS class
   */
  toggleClass(element, className) {
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to toggleClass');
        return false;
      }
      if (!className) {
        this.logger.warn('SafeDOM: Empty className provided to toggleClass');
        return false;
      }
      element.classList.toggle(className);
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error toggling CSS class', {
        className,
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Safely show element
   */
  show(element) {
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to show');
        return false;
      }
      element.style.display = '';
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error showing element', {
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Safely hide element
   */
  hide(element) {
    try {
      if (!element) {
        this.logger.warn('SafeDOM: Null element provided to hide');
        return false;
      }
      element.style.display = 'none';
      return true;
    } catch (error) {
      this.logger.error('SafeDOM: Error hiding element', {
        error: error.message
      });
      return false;
    }
  }
}
 
// Export for both ES modules and CommonJS
exports.SafeDOM = SafeDOM;
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    SafeDOM
  };
} else if (typeof window !== 'undefined') {
  window.SafeDOM = SafeDOM;
}
 
},{}],75:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "API_CONFIG", {
  enumerable: true,
  get: function () {
    return _configConstants.API_CONFIG;
  }
});
Object.defineProperty(exports, "BUSINESS_CONFIG", {
  enumerable: true,
  get: function () {
    return _configConstants.BUSINESS_CONFIG;
  }
});
Object.defineProperty(exports, "MESSAGES", {
  enumerable: true,
  get: function () {
    return _configConstants.MESSAGES;
  }
});
Object.defineProperty(exports, "UI_CONFIG", {
  enumerable: true,
  get: function () {
    return _configConstants.UI_CONFIG;
  }
});
exports.safeDOM = exports.logger = exports.errorHandler = void 0;
var _centralizedLogger = require("./centralized-logger.js");
var _safeDom = require("./safe-dom.js");
var _errorHandler = require("./error-handler.js");
var _configConstants = require("./config-constants.js");
/**
 * Utility Loader
 * 
 * Initializes and exposes debug-friendly utilities globally
 * Must be loaded before main application code
 */
 
// Import utilities
 
// Initialize utilities
const logger = exports.logger = new _centralizedLogger.CentralizedLogger();
const safeDOM = exports.safeDOM = new _safeDom.SafeDOM(logger);
const errorHandler = exports.errorHandler = new _errorHandler.ErrorHandler(logger);
 
// Expose utilities globally
if (typeof window !== 'undefined') {
  window.logger = logger;
  window.safeDOM = safeDOM;
  window.errorHandler = errorHandler;
 
  // Expose configuration constants
  window.API_CONFIG = _configConstants.API_CONFIG;
  window.UI_CONFIG = _configConstants.UI_CONFIG;
  window.MESSAGES = _configConstants.MESSAGES;
  window.BUSINESS_CONFIG = _configConstants.BUSINESS_CONFIG;
 
  // Initialize logger
  logger.info('Debug utilities loaded', {
    utilities: ['CentralizedLogger', 'SafeDOM', 'ErrorHandler', 'ConfigConstants'],
    timestamp: new Date().toISOString()
  });
}
 
// Export for module systems
 
},{"./centralized-logger.js":71,"./config-constants.js":72,"./error-handler.js":73,"./safe-dom.js":74}],76:[function(require,module,exports){
"use strict";
 
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _browserLoggingService = require("./utils/browser-logging-service.js");
var _debugLogger = require("./utils/debug-logger.js");
require("../../public/js/utils/utility-loader.js");
var _logger = require("../../public/js/modules/logger.js");
var _fileLogger = require("../../public/js/modules/file-logger.js");
var _eventBus = require("../../public/js/modules/event-bus.js");
var _settingsManager = require("../../public/js/modules/settings-manager.js");
var _uiManager = require("./components/ui-manager.js");
var _tokenManager = _interopRequireDefault(require("../../public/js/modules/token-manager.js"));
require("../../public/js/modules/disclaimer-modal.js");
require("../../public/js/modules/credentials-modal.js");
var _importSubsystem = require("./subsystems/import-subsystem.js");
var _exportSubsystem = require("./subsystems/export-subsystem.js");
var _operationManagerSubsystem = require("./subsystems/operation-manager-subsystem.js");
var _navigationSubsystem = require("./subsystems/navigation-subsystem.js");
var _connectionManagerSubsystem = require("./subsystems/connection-manager-subsystem.js");
var _realtimeCommunicationSubsystem = require("./subsystems/realtime-communication-subsystem.js");
var _authManagementSubsystem = require("./subsystems/auth-management-subsystem.js");
var _viewManagementSubsystem = require("./subsystems/view-management-subsystem.js");
var _globalTokenManagerSubsystem = require("./subsystems/global-token-manager-subsystem.js");
var _tokenNotificationSubsystem = require("./subsystems/token-notification-subsystem.js");
var _advancedRealtimeSubsystem = require("./subsystems/advanced-realtime-subsystem.js");
var _realtimeCollaborationUi = require("./components/realtime-collaboration-ui.js");
var _analyticsDashboardSubsystem = require("./subsystems/analytics-dashboard-subsystem.js");
var _analyticsDashboardUi = require("./components/analytics-dashboard-ui.js");
var _historyUi = _interopRequireDefault(require("./components/history-ui.js"));
var _loggingUiEnhanced = _interopRequireDefault(require("./components/logging-ui-enhanced.js"));
var _testingHub = _interopRequireDefault(require("./components/testing-hub.js"));
var _progressSubsystem = require("../../public/js/modules/progress-subsystem.js");
var _enhancedProgressSubsystem = require("./subsystems/enhanced-progress-subsystem.js");
var _enhancedTokenStatusSubsystem = require("./subsystems/enhanced-token-status-subsystem.js");
var _sessionSubsystem = require("../../public/js/modules/session-subsystem.js");
var _loggingSubsystem = require("../../public/js/modules/logging-subsystem.js");
var _historySubsystem = require("../../public/js/modules/history-subsystem.js");
var _populationSubsystem = require("../../public/js/modules/population-subsystem.js");
var _settingsSubsystem = require("../../public/js/modules/settings-subsystem.js");
var _localApiClient = require("../../public/js/modules/local-api-client.js");
var _pingoneClient = require("../../public/js/modules/pingone-client.js");
var _fileHandler = require("../../public/js/modules/file-handler.js");
var _versionManager = require("../../public/js/modules/version-manager.js");
var _tokenAlertModal = require("../../public/js/modules/token-alert-modal.js");
var _tokenRefreshHandler = _interopRequireDefault(require("../../public/js/modules/token-refresh-handler.js"));
var _socket = require("socket.io-client");
var _featureFlags = require("../shared/feature-flags.js");
// File: app.js
// Description: Main application entry point for PingOne user import tool
// 
// This file orchestrates the entire application, managing:
// - UI state and view transitions
// - File upload and CSV processing
// - Import/export/modify/delete operations
// - Real-time progress tracking via SSE
// - Settings management and population selection
// - Error handling and user feedback
// - Disclaimer agreement and feature flags
 
// Browser-compatible logging system
 
// Debug-friendly utilities
 
// Core utilities
 
// Components
 
// Modal components (needed for startup flow)
 
// Subsystems (new architecture)
 
// Modern subsystems (replacing legacy modules)
 
// Legacy modules (minimal usage, being phased out)
 
// Feature flags for gradual subsystem rollout
 
/**
 * Secret Field Toggle Component
 * 
 * Manages the visibility toggle for sensitive input fields (like API secrets).
 * Provides a secure way to show/hide sensitive data with visual feedback.
 * 
 * Features:
 * - Toggle between visible and masked input
 * - Visual eye icon that changes based on state
 * - Maintains actual value while showing masked version
 * - Prevents accidental exposure of sensitive data
 */
class SecretFieldToggle {
  constructor(inputElement, toggleElement) {
    this.input = inputElement;
    this.toggle = toggleElement;
    this.isVisible = false;
    this.originalValue = '';
    this.init();
  }
  init() {
    if (!this.input || !this.toggle) return;
    this.toggle.addEventListener('click', () => this.toggleVisibility());
    this.input.addEventListener('input', () => this.handleInput());
 
    // Initialize with masked state
    this.updateDisplay();
  }
  toggleVisibility() {
    this.isVisible = !this.isVisible;
    this.updateDisplay();
  }
  handleInput() {
    this.originalValue = this.input.value;
    if (!this.isVisible) {
      this.maskValue();
    }
  }
  updateDisplay() {
    if (this.isVisible) {
      this.input.value = this.originalValue;
      this.input.type = 'text';
      this.toggle.innerHTML = '<i class="fas fa-eye-slash"></i>';
      this.toggle.title = 'Hide';
    } else {
      this.maskValue();
      this.input.type = 'password';
      this.toggle.innerHTML = '<i class="fas fa-eye"></i>';
      this.toggle.title = 'Show';
    }
  }
  maskValue() {
    if (this.originalValue) {
      this.input.value = '•'.repeat(this.originalValue.length);
    }
  }
  getValue() {
    return this.originalValue;
  }
  setValue(value) {
    this.originalValue = value;
    this.updateDisplay();
  }
}
 
/**
 * Main Application Class
 * 
 * Orchestrates the entire PingOne user import tool application.
 * Manages all UI interactions, API calls, file processing, and state management.
 * 
 * Features:
 * - Subsystem-based architecture for better maintainability
 * - Centralized logging with correlation tracking
 * - Feature flags for gradual rollout
 * - Real-time progress tracking
 * - Comprehensive error handling
 */
class App {
  constructor() {
    // Initialize centralized logging
    this.logger = _featureFlags.FEATURE_FLAGS.USE_CENTRALIZED_LOGGING ? (0, _browserLoggingService.createLogger)({
      serviceName: 'pingone-import-app',
      enableServer: true,
      enableConsole: true
    }) : new _logger.Logger();
    this.logger.info('Application initialization started', {
      version: '6.3.0',
      featureFlags: _featureFlags.FEATURE_FLAGS
    });
 
    // Debug logging
    _debugLogger.debugLog.systemState('app', 'initialization_started', {
      version: '6.3.0',
      featureFlags: _featureFlags.FEATURE_FLAGS,
      userAgent: navigator.userAgent
    });
 
    // Core components
    this.eventBus = new _eventBus.EventBus();
    this.settingsManager = null;
    this.uiManager = null;
    this.tokenManager = null;
    this.fileHandler = null;
    this.versionManager = null;
 
    // API clients
    this.localClient = null;
 
    // UI Components
    this.globalTokenManager = null;
 
    // Modern subsystems (replacing legacy managers)
    this.progressSubsystem = null;
    this.enhancedProgressSubsystem = null;
    this.enhancedTokenStatusSubsystem = null;
    this.sessionSubsystem = null;
    this.loggingSubsystem = null;
    this.historySubsystem = null;
    this.populationSubsystem = null;
    this.settingsSubsystem = null;
 
    // Advanced real-time features
    this.advancedRealtimeSubsystem = null;
    this.realtimeCollaborationUI = null;
 
    // Subsystems (new architecture)
    this.subsystems = {};
    this.analyticsDashboardSubsystem = null;
    this.analyticsDashboardUI = null;
 
    // Application state
    this.isInitialized = false;
    this.currentView = 'home';
    this.socket = null;
 
    // Performance tracking
    this.logger.startTimer('app-initialization');
  }
 
  /**
   * Initialize the application
   */
  async init() {
    try {
      this.logger.info('Starting application initialization');
      this.updateStartupMessage('Initializing core components...');
 
      // Initialize core components
      await this.initializeCoreComponents();
      this.updateStartupMessage('Setting up subsystems...');
 
      // Initialize subsystems
      await this.initializeSubsystems();
      this.updateStartupMessage('Loading legacy components...');
 
      // Initialize legacy components (gradually being replaced)
      await this.initializeLegacyComponents();
      this.updateStartupMessage('Setting up event listeners...');
 
      // Set up event listeners
      this.setupEventListeners();
 
      // Set up modal completion listeners
      this.setupModalCompletionListeners();
      this.updateStartupMessage('Finalizing user interface...');
 
      // Initialize UI
      await this.initializeUI();
 
      // Mark as initialized
      this.isInitialized = true;
 
      // Hide startup screen
      this.hideStartupScreen();
      const initTime = this.logger.endTimer('app-initialization');
      this.logger.info('Application initialization completed', {
        initializationTime: `${initTime}ms`,
        subsystemsEnabled: Object.keys(this.subsystems).length
      });
    } catch (error) {
      this.logger.error('Application initialization failed', {
        error: error.message,
        stack: error.stack
      });
      throw error;
    }
  }
 
  /**
   * Hide the startup screen
   */
  hideStartupScreen() {
    try {
      const startupScreen = document.getElementById('startup-wait-screen');
      const appContainer = document.querySelector('.app-container');
      if (startupScreen) {
        this.logger.debug('Hiding startup wait screen');
        startupScreen.style.display = 'none';
      } else {
        this.logger.warn('Startup wait screen element not found');
      }
      if (appContainer) {
        appContainer.classList.remove('startup-loading');
      }
      this.logger.debug('Startup screen hidden successfully');
    } catch (error) {
      this.logger.error('Failed to hide startup screen', {
        error: error.message
      });
    }
  }
 
  /**
   * Initialize core components
   */
  async initializeCoreComponents() {
    this.logger.debug('Initializing core components');
 
    // API clients must be first as other components depend on it.
    this.localClient = new _localApiClient.LocalAPIClient(this.logger);
 
    // Initialize UIManager first as SettingsSubsystem depends on it.
    this.uiManager = new _uiManager.UIManager({
      logger: this.logger
    });
 
    // Initialize SettingsManager before SettingsSubsystem
    this.settingsManager = new _settingsManager.SettingsManager(this.logger.child({
      component: 'settings-manager'
    }));
    await this.settingsManager.init();
    this.logger.debug('Settings manager initialized');
 
    // SettingsSubsystem is a core component and must be initialized before others that depend on it.
    this.settingsSubsystem = new _settingsSubsystem.SettingsSubsystem(this.logger.child({
      subsystem: 'settings'
    }), this.uiManager, this.localClient, this.settingsManager,
    // Now properly initialized
    this.eventBus, null // credentialsManager - not available yet
    );
    await this.settingsSubsystem.init();
    this.subsystems.settings = this.settingsSubsystem;
    this.logger.debug('Settings subsystem initialized as a core component');
 
    // Initialize other core components that may depend on the above.
    this.tokenManager = new _tokenManager.default(this.logger, this.subsystems.settings.getAllSettings(), this.eventBus);
    this.fileHandler = new _fileHandler.FileHandler(this.logger, this.uiManager);
    this.versionManager = new _versionManager.VersionManager();
    try {
      this.pingOneClient = new _pingoneClient.PingOneClient();
      this.logger.debug('PingOne client created successfully');
    } catch (error) {
      this.logger.error('Failed to create PingOne client:', error);
      this.pingOneClient = null;
    }
    this.logger.debug('Core components initialized');
  }
 
  /**
   * Check if PingOne client is available and ready
   */
  isPingOneClientAvailable() {
    return this.pingOneClient !== null && typeof this.pingOneClient === 'object';
  }
 
  /**
   * Initialize subsystems with feature flags
   */
  async initializeSubsystems() {
    this.logger.info('Initializing subsystems...');
 
    // Defensive check for logger before proceeding
    if (!this.logger) {
      console.error('CRITICAL: Logger not initialized before subsystem setup. Aborting.');
      this.uiManager.showGlobalError('A critical error occurred during startup. Please refresh the page.');
      return;
    }
    try {
      // Subsystem Initialization with Feature Flags
      // Each subsystem is initialized only if its feature flag is enabled.
      // The main logger instance is passed directly to ensure stability.
 
      const subsystemsToInit = [{
        name: 'logging',
        flag: true,
        constructor: _loggingSubsystem.LoggingSubsystem,
        deps: [this.eventBus, this.logger]
      }, {
        name: 'navigation',
        flag: _featureFlags.FEATURE_FLAGS.USE_NAVIGATION_SUBSYSTEM,
        constructor: _navigationSubsystem.NavigationSubsystem,
        deps: [this.logger, this.uiManager, this.subsystems.settings]
      }, {
        name: 'connectionManager',
        flag: _featureFlags.FEATURE_FLAGS.USE_CONNECTION_MANAGER,
        constructor: _connectionManagerSubsystem.ConnectionManagerSubsystem,
        deps: [this.logger, this.uiManager, this.subsystems.settings, this.localClient]
      }, {
        name: 'realtimeManager',
        flag: _featureFlags.FEATURE_FLAGS.USE_REALTIME_SUBSYSTEM,
        constructor: _realtimeCommunicationSubsystem.RealtimeCommunicationSubsystem,
        deps: [this.logger, this.uiManager]
      }, {
        name: 'authManager',
        flag: _featureFlags.FEATURE_FLAGS.USE_AUTH_MANAGEMENT,
        constructor: _authManagementSubsystem.AuthManagementSubsystem,
        deps: [this.logger, this.uiManager, this.localClient, this.subsystems.settings]
      }, {
        name: 'viewManager',
        flag: _featureFlags.FEATURE_FLAGS.USE_VIEW_MANAGEMENT,
        constructor: _viewManagementSubsystem.ViewManagementSubsystem,
        deps: [this.logger, this.uiManager]
      }, {
        name: 'operationManager',
        flag: _featureFlags.FEATURE_FLAGS.USE_OPERATION_MANAGER,
        constructor: _operationManagerSubsystem.OperationManagerSubsystem,
        deps: [this.logger, this.uiManager, this.subsystems.settings, this.localClient]
      }, {
        name: 'population',
        flag: true,
        constructor: _populationSubsystem.PopulationSubsystem,
        deps: [this.eventBus, this.subsystems.settings, () => this.subsystems.logging, this.localClient]
      }, {
        name: 'history',
        flag: true,
        constructor: _historySubsystem.HistorySubsystem,
        deps: [this.eventBus, this.subsystems.settings, () => this.subsystems.logging]
      }, {
        name: 'import',
        flag: _featureFlags.FEATURE_FLAGS.USE_IMPORT_SUBSYSTEM,
        constructor: _importSubsystem.ImportSubsystem,
        deps: [this.logger, this.uiManager, this.localClient, this.subsystems.settings, this.eventBus, () => this.subsystems.population, () => this.subsystems.authManager]
      }, {
        name: 'export',
        flag: _featureFlags.FEATURE_FLAGS.USE_EXPORT_SUBSYSTEM,
        constructor: _exportSubsystem.ExportSubsystem,
        deps: [this.logger, this.uiManager, this.localClient, this.subsystems.settings, this.eventBus, () => this.subsystems.population]
      }, {
        name: 'analyticsDashboard',
        flag: _featureFlags.FEATURE_FLAGS.USE_ANALYTICS_DASHBOARD,
        constructor: _analyticsDashboardSubsystem.AnalyticsDashboardSubsystem,
        deps: [this.logger, this.eventBus, () => this.subsystems.advancedRealtime, this.progressSubsystem, this.sessionSubsystem]
      }, {
        name: 'advancedRealtime',
        flag: _featureFlags.FEATURE_FLAGS.USE_ADVANCED_REALTIME,
        constructor: _advancedRealtimeSubsystem.AdvancedRealtimeSubsystem,
        deps: [this.logger, this.eventBus, () => this.subsystems.realtimeManager, this.sessionSubsystem, this.progressSubsystem]
      }];
      for (const sub of subsystemsToInit) {
        if (sub.flag) {
          this.logger.debug(`Initializing ${sub.name} subsystem...`);
          // Resolve dependencies that are functions (lazy loading)
          const resolvedDeps = sub.deps.map(dep => typeof dep === 'function' ? dep() : dep);
          this.subsystems[sub.name] = new sub.constructor(...resolvedDeps);
          await this.subsystems[sub.name].init();
          this.logger.info(`${sub.name} subsystem initialized.`);
        }
      }
 
      // Initialize UI components that depend on subsystems
      if (this.subsystems.advancedRealtime) {
        this.realtimeCollaborationUI = new _realtimeCollaborationUi.RealtimeCollaborationUI(this.eventBus, this.logger);
        this.realtimeCollaborationUI.init();
      }
      this.logger.info('All subsystems initialized successfully.');
    } catch (error) {
      this.logger.error('Subsystem initialization failed', {
        error: error.message,
        stack: error.stack
      });
      throw error;
    }
 
    // Global Token Manager Subsystem
    this.subsystems.globalTokenManager = new _globalTokenManagerSubsystem.GlobalTokenManagerSubsystem(this.logger.child({
      subsystem: 'globalTokenManager'
    }), this.eventBus);
    await this.subsystems.globalTokenManager.init();
    this.logger.debug('Global Token Manager subsystem initialized');
 
    // Initialize Token Notification Subsystem
    this.subsystems.tokenNotification = new _tokenNotificationSubsystem.TokenNotificationSubsystem(this.logger.child({
      subsystem: 'token-notification'
    }), this.eventBus, this.subsystems.navigation);
    await this.subsystems.tokenNotification.init();
    this.logger.debug('Token Notification subsystem initialized');
 
    // Initialize Enhanced Progress Subsystem
    // Fixed progress subsystem initialization
    this.enhancedProgressSubsystem = new _enhancedProgressSubsystem.EnhancedProgressSubsystem(this.logger.child({
      subsystem: 'enhanced-progress'
    }), this.uiManager, this.eventBus, this.subsystems.realtimeManager);
    await this.enhancedProgressSubsystem.init();
    this.subsystems.enhancedProgress = this.enhancedProgressSubsystem;
    this.logger.debug('Enhanced Progress subsystem initialized');
 
    // Initialize Enhanced Token Status Subsystem
    this.enhancedTokenStatusSubsystem = new _enhancedTokenStatusSubsystem.EnhancedTokenStatusSubsystem(this.logger.child({
      subsystem: 'enhanced-token-status'
    }), this.eventBus, this.uiManager);
    await this.enhancedTokenStatusSubsystem.init();
    this.subsystems.enhancedTokenStatus = this.enhancedTokenStatusSubsystem;
    this.logger.debug('Enhanced Token Status subsystem initialized');
    this.logger.info('All subsystems initialized successfully', {
      subsystemCount: Object.keys(this.subsystems).length,
      enabledSubsystems: Object.keys(this.subsystems)
    });
  }
 
  /**
   * Initialize remaining legacy components (minimal usage)
   */
  async initializeLegacyComponents() {
    this.logger.debug('Initializing remaining legacy components');
 
    // Note: Most legacy managers have been replaced by modern subsystems
    // Only keeping minimal legacy components that haven't been fully migrated yet
 
    this.logger.debug('Legacy components initialized (minimal set)');
  }
  /**
   * Set up event listeners and EventBus patterns
   */
  setupEventListeners() {
    this.logger.debug('Setting up event listeners and EventBus patterns');
 
    // Global error handler with EventBus integration
    window.addEventListener('error', event => {
      const errorData = {
        message: event.message,
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
        error: event.error?.stack
      };
      this.logger.error('Global error caught', errorData);
      this.eventBus.emit('app:global-error', errorData);
    });
 
    // Unhandled promise rejection handler with EventBus integration
    window.addEventListener('unhandledrejection', event => {
      const rejectionData = {
        reason: event.reason,
        promise: event.promise
      };
      this.logger.error('Unhandled promise rejection', rejectionData);
      this.eventBus.emit('app:unhandled-rejection', rejectionData);
    });
 
    // Performance monitoring with EventBus integration
    window.addEventListener('load', () => {
      const performanceData = {
        loadTime: performance.now(),
        timing: performance.timing
      };
      this.logger.info('Page load completed', performanceData);
      this.eventBus.emit('app:page-loaded', performanceData);
    });
 
    // Settings save feedback event listeners
    window.addEventListener('settings:save-success', event => {
      const statusBox = document.getElementById('settings-status-box');
      if (statusBox) {
        statusBox.textContent = event.detail.message;
        statusBox.className = 'status-message status-success';
        statusBox.style.display = 'flex';
        setTimeout(() => {
          statusBox.style.display = 'none';
        }, 5000);
      }
    });
    window.addEventListener('settings:save-error', event => {
      const statusBox = document.getElementById('settings-status-box');
      if (statusBox) {
        statusBox.textContent = event.detail.message;
        statusBox.className = 'status-message status-error';
        statusBox.style.display = 'flex';
        setTimeout(() => {
          statusBox.style.display = 'none';
        }, 8000);
      }
    });
 
    // EventBus listeners for subsystem coordination
    this.setupEventBusListeners();
 
    // Setup main UI button event listeners
    this.setupMainUIEventListeners();
    this.logger.debug('Event listeners and EventBus patterns set up');
  }
 
  /**
   * Set up main UI event listeners for navigation and buttons
   */
  setupMainUIEventListeners() {
    this.logger.debug('Setting up main UI event listeners');
    try {
      // Note: Navigation cards are handled by ViewManagementSubsystem
      // Only set up non-navigation UI event listeners here
 
      // File input handlers for import
      const fileInput = document.getElementById('csv-file');
      if (fileInput) {
        fileInput.addEventListener('change', e => {
          this.logger.debug('File input changed');
          this.handleFileSelection(e);
        });
      }
 
      // Drop zone handlers for import
      const dropZone = document.getElementById('import-drop-zone');
      if (dropZone) {
        dropZone.addEventListener('click', e => {
          e.preventDefault();
          this.logger.debug('Drop zone clicked');
          if (fileInput) {
            fileInput.click();
          }
        });
        dropZone.addEventListener('dragover', e => {
          e.preventDefault();
          dropZone.classList.add('dragover');
        });
        dropZone.addEventListener('dragleave', e => {
          e.preventDefault();
          dropZone.classList.remove('dragover');
        });
        dropZone.addEventListener('drop', e => {
          e.preventDefault();
          dropZone.classList.remove('dragover');
          this.logger.debug('File dropped');
          this.handleFileDrop(e);
        });
      }
 
      // Cancel import button
      const cancelImportBtn = document.getElementById('cancel-import-btn');
      if (cancelImportBtn) {
        cancelImportBtn.addEventListener('click', e => {
          e.preventDefault();
          this.logger.debug('Cancel import button clicked');
          this.cancelImport();
        });
      }
 
      // DIRECT NAVIGATION FIX - Add navigation event listeners as fallback
      this.logger.debug('Setting up direct navigation event listeners as fallback');
      this.setupDirectNavigation();
      this.logger.debug('Main UI event listeners set up successfully');
    } catch (error) {
      this.logger.error('Failed to set up main UI event listeners', {
        error: error.message
      });
    }
  }
 
  /**
   * Set up EventBus listeners for subsystem coordination
   */
  setupEventBusListeners() {
    this.logger.debug('Setting up EventBus listeners for subsystem coordination');
 
    // Application lifecycle events
    this.eventBus.on('app:init-complete', data => {
      this.logger.info('Application initialization complete', data);
    });
    this.eventBus.on('app:shutdown', data => {
      this.logger.info('Application shutdown initiated', data);
    });
 
    // Subsystem communication events
    this.eventBus.on('subsystem:error', data => {
      this.logger.error('Subsystem error occurred', data);
    });
    this.eventBus.on('subsystem:ready', data => {
      this.logger.debug('Subsystem ready', data);
    });
 
    // Operation lifecycle events
    this.eventBus.on('navigation:view-changed', _ref => {
      let {
        newView
      } = _ref;
      this.currentView = newView;
      this.logger.info(`View changed to: ${newView}`);
      if ((0, _featureFlags.isFeatureEnabled)('ANALYTICS_DASHBOARD') && this.analyticsDashboardUI) {
        if (newView === 'analytics') {
          this.analyticsDashboardUI.show();
        } else {
          this.analyticsDashboardUI.hide();
        }
      }
    });
    this.eventBus.on('operation:started', data => {
      this.logger.info('Operation started', data);
    });
    this.eventBus.on('operation:completed', data => {
      this.logger.info('Operation completed', data);
    });
    this.eventBus.on('operation:failed', data => {
      this.logger.error('Operation failed', data);
    });
 
    // Progress and status events
    this.eventBus.on('progress:updated', data => {
      this.logger.debug('Progress updated', data);
    });
    this.eventBus.on('status:changed', data => {
      this.logger.debug('Status changed', data);
    });
    this.logger.debug('EventBus listeners set up for subsystem coordination');
  }
 
  /**
   * Set up modal completion listeners
   */
  setupModalCompletionListeners() {
    try {
      // Listen for credentials modal completion
      document.addEventListener('credentials-modal-completed', event => {
        this.logger.info('🔄 LOADING: Credentials modal completed', event.detail);
        this.showModalLoading('Finalizing Setup...', 'Completing your PingOne Import Tool configuration.');
 
        // Hide loading after a brief delay
        setTimeout(() => {
          this.hideModalLoading();
        }, 1500);
      });
 
      // Listen for any modal events that might indicate completion
      document.addEventListener('application_enabled_after_credentials', event => {
        this.logger.info('🔄 LOADING: Application enabled after credentials');
        this.showModalLoading('Almost Ready...', 'Finalizing your workspace setup.');
        setTimeout(() => {
          this.hideModalLoading();
        }, 1000);
      });
      this.logger.debug('Modal completion listeners set up');
    } catch (error) {
      this.logger.error('Failed to set up modal completion listeners', {
        error: error.message
      });
    }
  }
 
  /**
   * Show modal loading overlay
   */
  showModalLoading() {
    let title = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Loading...';
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Please wait while we set up your experience.';
    try {
      const overlay = document.getElementById('modal-loading-overlay');
      const titleElement = document.getElementById('modal-loading-title');
      const messageElement = document.getElementById('modal-loading-message');
      if (overlay && titleElement && messageElement) {
        titleElement.textContent = title;
        messageElement.textContent = message;
        overlay.classList.remove('fade-out');
        overlay.classList.add('fade-in');
        overlay.style.display = 'flex';
        this.logger.debug('🔄 LOADING: Modal loading shown', {
          title,
          message
        });
      }
    } catch (error) {
      this.logger.error('🔄 LOADING: Failed to show modal loading', {
        error: error.message
      });
    }
  }
 
  /**
   * Hide modal loading overlay
   */
  hideModalLoading() {
    try {
      const overlay = document.getElementById('modal-loading-overlay');
      if (overlay) {
        overlay.classList.remove('fade-in');
        overlay.classList.add('fade-out');
 
        // Hide after animation completes
        setTimeout(() => {
          overlay.style.display = 'none';
          overlay.classList.remove('fade-out');
        }, 300);
        this.logger.debug('🔄 LOADING: Modal loading hidden');
      }
    } catch (error) {
      this.logger.error('🔄 LOADING: Failed to hide modal loading', {
        error: error.message
      });
    }
  }
 
  /**
   * Update startup screen message
   */
  updateStartupMessage(message) {
    try {
      const startupScreen = document.getElementById('startup-wait-screen');
      const textElement = startupScreen?.querySelector('.startup-text p');
      if (textElement) {
        textElement.textContent = message;
        this.logger.debug('🔄 LOADING: Startup message updated', {
          message
        });
      }
    } catch (error) {
      this.logger.error('🔄 LOADING: Failed to update startup message', {
        error: error.message
      });
    }
  }
 
  /**
   * Set up direct navigation event listeners as fallback
   * This is used when the ViewManagementSubsystem is not working properly
   */
  setupDirectNavigation() {
    this.logger.debug('🔧 DIRECT NAV: Setting up direct navigation event listeners');
    try {
      // Find all navigation elements
      const navElements = document.querySelectorAll('[data-view]');
      this.logger.debug(`🔧 DIRECT NAV: Found ${navElements.length} navigation elements`);
      if (navElements.length === 0) {
        this.logger.warn('🔧 DIRECT NAV: No navigation elements found with [data-view] attribute');
        return;
      }
 
      // Add click listeners to navigation elements
      navElements.forEach((element, index) => {
        const view = element.getAttribute('data-view');
        this.logger.debug(`🔧 DIRECT NAV: Setting up listener for ${view} (element ${index})`);
 
        // Remove any existing listeners first
        element.removeEventListener('click', this.handleDirectNavigation);
 
        // Add new listener
        const clickHandler = e => {
          e.preventDefault();
          e.stopPropagation();
          this.logger.info(`🔧 DIRECT NAV: Navigation clicked: ${view}`);
          this.directShowView(view);
        };
        element.addEventListener('click', clickHandler);
 
        // Store the handler for cleanup if needed
        element._directNavHandler = clickHandler;
      });
      this.logger.info('🔧 DIRECT NAV: Direct navigation setup completed successfully');
 
      // Also set up settings page buttons
      this.setupSettingsPageButtons();
    } catch (error) {
      this.logger.error('🔧 DIRECT NAV: Failed to set up direct navigation', {
        error: error.message
      });
    }
  }
 
  /**
   * Set up settings page button event listeners
   */
  setupSettingsPageButtons() {
    this.logger.debug('🔧 SETTINGS: Setting up settings page button listeners');
    try {
      // Save Settings button
      const saveSettingsBtn = document.getElementById('save-settings');
      if (saveSettingsBtn) {
        saveSettingsBtn.addEventListener('click', e => {
          e.preventDefault();
          this.logger.info('🔧 SETTINGS: Save Settings clicked');
          this.handleSaveSettings();
        });
        this.logger.debug('🔧 SETTINGS: Save Settings button listener added');
      }
 
      // Test Connection button
      const testConnectionBtn = document.getElementById('test-connection-btn');
      if (testConnectionBtn) {
        testConnectionBtn.addEventListener('click', e => {
          e.preventDefault();
          this.logger.info('🔧 SETTINGS: Test Connection clicked');
          this.handleTestConnection();
        });
        this.logger.debug('🔧 SETTINGS: Test Connection button listener added');
      }
 
      // Get Token button
      const getTokenBtn = document.getElementById('get-token-btn');
      if (getTokenBtn) {
        getTokenBtn.addEventListener('click', e => {
          e.preventDefault();
          this.logger.info('🔧 SETTINGS: Get Token clicked');
          this.handleGetToken();
        });
        this.logger.debug('🔧 SETTINGS: Get Token button listener added');
      }
 
      // Toggle API Secret Visibility button
      const toggleSecretBtn = document.getElementById('toggle-api-secret-visibility');
      if (toggleSecretBtn) {
        toggleSecretBtn.addEventListener('click', e => {
          e.preventDefault();
          this.logger.info('🔧 SETTINGS: Toggle Secret Visibility clicked');
          this.handleToggleSecretVisibility();
        });
        this.logger.debug('🔧 SETTINGS: Toggle Secret Visibility button listener added');
      }
      this.logger.info('🔧 SETTINGS: Settings page buttons setup completed');
    } catch (error) {
      this.logger.error('🔧 SETTINGS: Failed to set up settings page buttons', {
        error: error.message
      });
    }
  }
 
  /**
   * Handle Save Settings button click
   */
  async handleSaveSettings() {
    this.logger.info('🔧 SETTINGS: Saving settings...');
 
    // Debug logging
    _debugLogger.debugLog.userAction('save_settings', 'save-settings-button', {
      timestamp: Date.now()
    });
    try {
      // Get form values
      const environmentId = document.getElementById('environment-id')?.value;
      const clientId = document.getElementById('api-client-id')?.value;
      const clientSecret = document.getElementById('api-secret')?.value;
      const region = document.getElementById('region')?.value;
      const rateLimit = document.getElementById('rate-limit')?.value;
      const populationId = document.getElementById('population-id')?.value;
      const settings = {
        environmentId,
        apiClientId: clientId,
        // Fix: use apiClientId instead of clientId
        apiSecret: clientSecret,
        // Fix: use apiSecret instead of clientSecret
        region,
        rateLimit: parseInt(rateLimit) || 90,
        populationId
      };
      this.logger.debug('🔧 SETTINGS: Settings to save', {
        ...settings,
        clientSecret: '[HIDDEN]'
      });
 
      // Use settings manager if available
      if (this.settingsManager && typeof this.settingsManager.saveSettings === 'function') {
        await this.settingsManager.saveSettings(settings);
        this.showSettingsStatus('Settings saved successfully!', 'success');
      } else {
        // Fallback: save to localStorage and send to server
        localStorage.setItem('pingone-settings', JSON.stringify(settings));
 
        // Send to server
        const response = await fetch('/api/settings', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(settings)
        });
        if (response.ok) {
          const result = await response.json();
          this.showSettingsStatus('Settings saved successfully!', 'success');
          this.logger.info('🔧 SETTINGS: Settings saved successfully', result);
        } else {
          const errorData = await response.json().catch(() => ({
            error: 'Unknown error'
          }));
          throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
        }
      }
    } catch (error) {
      this.logger.error('🔧 SETTINGS: Failed to save settings', {
        error: error.message
      });
 
      // Debug logging
      _debugLogger.debugLog.error('settings', 'Save settings failed', error, {
        action: 'save_settings',
        timestamp: Date.now()
      });
      this.showSettingsStatus(`Failed to save settings: ${error.message}`, 'error');
    }
  }
 
  /**
   * Load settings and populate form fields
   * Called by ViewManagementSubsystem when settings view is initialized
   * 
   * CRITICAL: This method is required by ViewManagementSubsystem.initializeSettingsView()
   * DO NOT remove or rename this method without updating ViewManagementSubsystem
   * Last fixed: 2025-07-21 - Missing method caused settings page to not load credentials
   * 
   * @returns {Promise<Object>} Loaded settings object
   */
  async loadSettings() {
    this.logger.info('🔧 SETTINGS: Loading settings for form population...');
    try {
      // Use SettingsSubsystem if available
      if (this.settingsSubsystem && typeof this.settingsSubsystem.loadSettings === 'function') {
        this.logger.debug('🔧 SETTINGS: Using SettingsSubsystem to load settings');
        const settings = await this.settingsSubsystem.loadSettings();
        this.populateSettingsForm(settings);
        return settings;
      }
 
      // Fallback to direct API call (same as credentials modal)
      this.logger.debug('🔧 SETTINGS: Using direct API call to load settings');
      try {
        const response = await fetch('/api/settings');
        if (response.ok) {
          const settings = await response.json();
          this.populateSettingsForm(settings);
          return settings;
        }
      } catch (error) {
        this.logger.error('🔧 SETTINGS: Failed to load settings from API', {
          error: error.message
        });
        this.showSettingsStatus(`Failed to load settings: ${error.message}`, 'error');
        return {};
      }
    } catch (error) {
      this.logger.error('🔧 SETTINGS: Failed to load settings', {
        error: error.message
      });
      this.showSettingsStatus(`Failed to load settings: ${error.message}`, 'error');
      return {};
    }
  }
 
  /**
   * Populate settings form fields with loaded data
   */
  populateSettingsForm(settings) {
    this.logger.debug('🔧 SETTINGS: Populating form fields with settings data');
    try {
      // Map settings to form fields (handle both naming conventions)
      const fieldMappings = {
        'environment-id': settings.environmentId || settings['environment-id'] || '',
        'api-client-id': settings.apiClientId || settings['api-client-id'] || '',
        'api-secret': settings.apiSecret || settings['api-secret'] || '',
        'region': settings.region || 'NorthAmerica',
        'population-id': settings.populationId || settings['population-id'] || '',
        'rate-limit': settings.rateLimit || settings['rate-limit'] || 90
      };
 
      // Populate each form field
      Object.entries(fieldMappings).forEach(_ref2 => {
        let [fieldId, value] = _ref2;
        const field = document.getElementById(fieldId);
        if (field && value) {
          field.value = value;
          this.logger.debug(`🔧 SETTINGS: Populated field ${fieldId}`, {
            hasValue: !!value
          });
        }
      });
      this.logger.info('🔧 SETTINGS: Form fields populated successfully');
    } catch (error) {
      this.logger.error('🔧 SETTINGS: Failed to populate form fields', {
        error: error.message
      });
    }
  }
 
  /**
   * Handle Test Connection button click
   */
  async handleTestConnection() {
    this.logger.info('🔧 SETTINGS: Testing connection...');
 
    // Debug logging
    _debugLogger.debugLog.userAction('test_connection', 'test-connection-btn', {
      timestamp: Date.now()
    });
    try {
      this.showSettingsStatus('Testing connection...', 'info');
 
      // Use connection manager if available
      if (this.subsystems.connectionManager && typeof this.subsystems.connectionManager.testConnection === 'function') {
        const result = await this.subsystems.connectionManager.testConnection();
        if (result.success) {
          this.showSettingsStatus('Connection test successful!', 'success');
        } else {
          this.showSettingsStatus(`Connection test failed: ${result.error}`, 'error');
        }
      } else {
        // Fallback: test connection directly
        // CRITICAL: This MUST be a GET request to match server-side endpoint
        // Server endpoint: routes/pingone-proxy-fixed.js - router.get('/test-connection')
        // DO NOT change to POST without updating server-side endpoint
        // Last fixed: 2025-07-21 - HTTP method mismatch caused 400 Bad Request errors
        const response = await fetch('/api/pingone/test-connection', {
          method: 'GET',
          // MUST match server endpoint method
          headers: {
            'Content-Type': 'application/json'
          }
        });
        const result = await response.json();
        if (result.success) {
          this.showSettingsStatus('Connection test successful!', 'success');
        } else {
          this.showSettingsStatus(`Connection test failed: ${result.error}`, 'error');
        }
      }
    } catch (error) {
      this.logger.error('🔧 SETTINGS: Connection test failed', {
        error: error.message
      });
      this.showSettingsStatus(`Connection test failed: ${error.message}`, 'error');
    }
  }
 
  /**
   * Handle Get Token button click
   */
  async handleGetToken() {
    this.logger.info('🔧 SETTINGS: Getting token...');
 
    // Debug logging
    _debugLogger.debugLog.userAction('get_token', 'get-token-btn', {
      timestamp: Date.now()
    });
    try {
      this.showSettingsStatus('Getting token...', 'info');
 
      // Use token manager if available
      if (this.tokenManager && typeof this.tokenManager.getToken === 'function') {
        const token = await this.tokenManager.getToken();
        if (token) {
          this.showSettingsStatus('Token acquired successfully!', 'success');
        } else {
          this.showSettingsStatus('Failed to get token', 'error');
        }
      } else {
        // Fallback: get token directly
        const response = await fetch('/api/pingone/token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        const result = await response.json();
        if (result.access_token) {
          this.showSettingsStatus('Token acquired successfully!', 'success');
        } else {
          this.showSettingsStatus('Failed to get token', 'error');
        }
      }
    } catch (error) {
      this.logger.error('🔧 SETTINGS: Failed to get token', {
        error: error.message
      });
      this.showSettingsStatus(`Failed to get token: ${error.message}`, 'error');
    }
  }
 
  /**
   * Handle Toggle Secret Visibility button click
   */
  handleToggleSecretVisibility() {
    this.logger.debug('🔧 SETTINGS: Toggling secret visibility');
    try {
      const secretInput = document.getElementById('api-secret');
      const toggleBtn = document.getElementById('toggle-api-secret-visibility');
      const icon = toggleBtn?.querySelector('i');
      if (secretInput && toggleBtn && icon) {
        if (secretInput.type === 'password') {
          secretInput.type = 'text';
          icon.className = 'fas fa-eye-slash';
          this.logger.debug('🔧 SETTINGS: Secret visibility: shown');
        } else {
          secretInput.type = 'password';
          icon.className = 'fas fa-eye';
          this.logger.debug('🔧 SETTINGS: Secret visibility: hidden');
        }
      }
    } catch (error) {
      this.logger.error('🔧 SETTINGS: Failed to toggle secret visibility', {
        error: error.message
      });
    }
  }
 
  /**
   * Show status message in settings page
   */
  showSettingsStatus(message) {
    let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
    try {
      const statusElement = document.getElementById('settings-action-status');
      const messageElement = statusElement?.querySelector('.status-message');
      const iconElement = statusElement?.querySelector('.status-icon');
      if (statusElement && messageElement && iconElement) {
        // Set message
        messageElement.textContent = message;
 
        // Set icon based on type
        const icons = {
          'success': 'fas fa-check-circle',
          'error': 'fas fa-exclamation-circle',
          'info': 'fas fa-info-circle',
          'warning': 'fas fa-exclamation-triangle'
        };
        iconElement.className = icons[type] || icons.info;
 
        // Set CSS class for styling
        statusElement.className = `action-status ${type}`;
        statusElement.style.display = 'block';
 
        // Auto-hide after 5 seconds for success/info messages
        if (type === 'success' || type === 'info') {
          setTimeout(() => {
            statusElement.style.display = 'none';
          }, 5000);
        }
        this.logger.debug(`🔧 SETTINGS: Status shown: ${type} - ${message}`);
      }
    } catch (error) {
      this.logger.error('🔧 SETTINGS: Failed to show status', {
        error: error.message
      });
    }
  }
 
  /**
   * Direct view switching (bypasses subsystems)
   */
  async directShowView(view) {
    this.logger.info(`🔧 DIRECT NAV: Switching to view: ${view}`);
 
    // Debug logging
    _debugLogger.debugLog.navigation(this.currentView, view, {
      method: 'direct_navigation',
      timestamp: Date.now()
    });
    try {
      // Hide all views
      const allViews = document.querySelectorAll('.view, .view-container');
      this.logger.debug(`🔧 DIRECT NAV: Found ${allViews.length} view containers to hide`);
      allViews.forEach(viewElement => {
        viewElement.style.display = 'none';
        viewElement.classList.remove('active');
      });
 
      // Show target view
      const targetView = document.getElementById(`${view}-view`);
      if (targetView) {
        targetView.style.display = 'block';
        targetView.classList.add('active');
        this.logger.info(`🔧 DIRECT NAV: Successfully showed ${view}-view`);
 
        // Update navigation state
        this.updateDirectNavigationState(view);
 
        // Update current view
        this.currentView = view;
 
        // Update page title
        this.updatePageTitle(view);
        this.logger.info(`🔧 DIRECT NAV: Navigation to ${view} completed successfully`);
      } else {
        this.logger.error(`🔧 DIRECT NAV: View element not found: ${view}-view`);
      }
    } catch (error) {
      this.logger.error(`🔧 DIRECT NAV: Failed to show view ${view}`, {
        error: error.message
      });
    }
  }
 
  /**
   * Update navigation state for direct navigation
   */
  updateDirectNavigationState(view) {
    try {
      // Update active navigation items
      const navElements = document.querySelectorAll('[data-view]');
      navElements.forEach(element => {
        const elementView = element.getAttribute('data-view');
        if (elementView === view) {
          element.classList.add('active');
        } else {
          element.classList.remove('active');
        }
      });
      this.logger.debug(`🔧 DIRECT NAV: Updated navigation state for ${view}`);
    } catch (error) {
      this.logger.error('🔧 DIRECT NAV: Failed to update navigation state', {
        error: error.message
      });
    }
  }
 
  /**
   * Update page title
   */
  updatePageTitle(view) {
    try {
      const titles = {
        'home': 'Home',
        'import': 'Import Users',
        'export': 'Export Users',
        'modify': 'Modify Users',
        'delete-csv': 'Delete Users',
        'settings': 'Settings',
        'logs': 'Logs',
        'history': 'History'
      };
      const title = titles[view] || 'PingOne Import Tool';
      document.title = `${title} - PingOne Import Tool v6.5.1.1`;
      this.logger.debug(`🔧 DIRECT NAV: Updated page title to: ${document.title}`);
    } catch (error) {
      this.logger.error('🔧 DIRECT NAV: Failed to update page title', {
        error: error.message
      });
    }
  }
 
  /**
   * Initialize UI
   */
  async initializeUI() {
    this.logger.debug('Initializing UI');
 
    // Use view management subsystem if available
    if (this.subsystems.viewManager) {
      await this.subsystems.viewManager.showView(this.currentView);
    } else {
      // Fallback to legacy view management
      await this.legacyShowView(this.currentView);
    }
    this.logger.debug('UI initialized');
  }
 
  /**
   * Show view using subsystem or fallback to legacy
   */
  async showView(view) {
    this.logger.debug('Showing view', {
      view,
      useSubsystem: !!this.subsystems.viewManager
    });
    if (this.subsystems.viewManager) {
      return await this.subsystems.viewManager.showView(view);
    } else {
      return await this.legacyShowView(view);
    }
  }
 
  /**
   * Legacy view management (fallback)
   */
  async legacyShowView(view) {
    this.logger.debug('Using legacy view management', {
      view
    });
    // Legacy implementation would go here
    this.currentView = view;
  }
 
  /**
   * Start import operation
   */
  async startImport() {
    this.logger.info('Starting import operation');
    if (this.subsystems.importManager) {
      return await this.subsystems.importManager.startImport();
    } else {
      // Fallback to legacy import
      this.logger.warn('Using legacy import - subsystem not available');
      return await this.legacyStartImport();
    }
  }
 
  /**
   * Start export operation
   */
  async startExport() {
    this.logger.info('Starting export operation');
    if (this.subsystems.exportManager) {
      return await this.subsystems.exportManager.startExport();
    } else {
      // Fallback to legacy export
      this.logger.warn('Using legacy export - subsystem not available');
      return await this.legacyStartExport();
    }
  }
 
  /**
   * Get authentication token
   */
  async getToken() {
    this.logger.debug('Getting authentication token');
    if (this.subsystems.authManager) {
      return await this.subsystems.authManager.getToken();
    } else {
      // Fallback to legacy token management
      this.logger.warn('Using legacy token management - subsystem not available');
      return await this.tokenManager.getToken();
    }
  }
 
  /**
   * Legacy methods (to be removed as subsystems are fully integrated)
   */
  async legacyStartImport() {
    this.logger.debug('Legacy import method called');
    // Legacy implementation
  }
  async legacyStartExport() {
    this.logger.debug('Legacy export method called');
    // Legacy implementation
  }
 
  /**
   * Navigate to a specific view
   */
  navigateToView(viewName) {
    this.logger.debug('Navigating to view', {
      viewName
    });
    try {
      // Use view management subsystem if available
      if (this.subsystems.viewManager) {
        this.subsystems.viewManager.showView(viewName);
      } else {
        // Fallback to legacy view management
        this.legacyShowView(viewName);
      }
      this.currentView = viewName;
      this.logger.info('Navigation completed', {
        viewName
      });
    } catch (error) {
      this.logger.error('Navigation failed', {
        viewName,
        error: error.message
      });
    }
  }
 
  /**
   * Handle file selection from input
   */
  handleFileSelection(event) {
    this.logger.debug('Handling file selection');
    try {
      const files = event.target.files;
      if (files && files.length > 0) {
        const file = files[0];
        this.logger.info('File selected', {
          fileName: file.name,
          fileSize: file.size,
          fileType: file.type
        });
 
        // Use import subsystem if available
        if (this.subsystems.importManager) {
          this.subsystems.importManager.handleFileSelection(file);
        } else {
          this.logger.warn('Import subsystem not available, using legacy import');
          if (this.fileHandler && typeof this.fileHandler.handleFile === 'function') {
            this.fileHandler.handleFile(file);
          } else {
            this.logger.error('No file handling method available');
            this.showMessage('File handling is not available. Please refresh the page.', 'error');
          }
        }
      }
    } catch (error) {
      this.logger.error('File selection handling failed', {
        error: error.message
      });
    }
  }
 
  /**
   * Handle file drop from drag and drop
   */
  handleFileDrop(event) {
    this.logger.debug('Handling file drop');
    try {
      const files = event.dataTransfer.files;
      if (files && files.length > 0) {
        const file = files[0];
        this.logger.info('File dropped', {
          fileName: file.name,
          fileSize: file.size,
          fileType: file.type
        });
 
        // Use import subsystem if available
        if (this.subsystems.importManager) {
          this.subsystems.importManager.handleFileSelection(file);
        } else {
          this.logger.warn('Import subsystem not available, using legacy import');
          if (this.fileHandler && typeof this.fileHandler.handleFile === 'function') {
            this.fileHandler.handleFile(file);
          } else {
            this.logger.error('No file handling method available');
            this.showMessage('File handling is not available. Please refresh the page.', 'error');
          }
        }
      }
    } catch (error) {
      this.logger.error('File drop handling failed', {
        error: error.message
      });
    }
  }
 
  /**
   * Cancel import operation
   */
  cancelImport() {
    this.logger.debug('Cancelling import operation');
    try {
      // Use import subsystem if available
      if (this.subsystems.importManager) {
        this.subsystems.importManager.cancelImport();
      } else {
        this.logger.warn('Import subsystem not available, using legacy cancel');
        this.legacyCancelImport();
      }
      this.logger.info('Import cancellation requested');
    } catch (error) {
      this.logger.error('Import cancellation failed', {
        error: error.message
      });
    }
  }
 
  /**
   * Enable tool after disclaimer acceptance
   */
  enableToolAfterDisclaimer() {
    this.logger.info('Enabling tool after disclaimer acceptance');
    try {
      // Show loading overlay during transition
      this.showModalLoading('Setting up...', 'Preparing your PingOne Import Tool experience.');
 
      // Hide startup screen if still visible
      this.hideStartupScreen();
 
      // Ensure UI is properly initialized and responsive
      if (this.uiManager && typeof this.uiManager.enableUI === 'function') {
        this.uiManager.enableUI();
      }
 
      // Initialize event listeners if not already done
      if (!this.eventListenersSetup) {
        this.setupEventListeners();
        this.eventListenersSetup = true;
      }
 
      // Enable all subsystems
      Object.values(this.subsystems).forEach(subsystem => {
        if (subsystem && typeof subsystem.enable === 'function') {
          subsystem.enable();
        }
      });
 
      // Remove any disabled states from the app container
      const appContainer = document.querySelector('.app-container');
      if (appContainer) {
        appContainer.classList.remove('disabled', 'modal-active');
        appContainer.style.pointerEvents = 'auto';
      }
 
      // Enable all buttons and interactive elements
      const buttons = document.querySelectorAll('button, .btn');
      buttons.forEach(button => {
        button.disabled = false;
        button.style.pointerEvents = 'auto';
      });
      this.logger.info('Tool enabled successfully after disclaimer');
 
      // Hide loading overlay after a brief delay to show completion
      setTimeout(() => {
        this.hideModalLoading();
      }, 1000);
    } catch (error) {
      this.logger.error('Failed to enable tool after disclaimer', {
        error: error.message
      });
      // Hide loading overlay on error too
      this.hideModalLoading();
    }
  }
 
  /**
   * Get application health status
   */
  getHealthStatus() {
    return {
      initialized: this.isInitialized,
      subsystems: Object.keys(this.subsystems).reduce((status, key) => {
        status[key] = this.subsystems[key].isInitialized || false;
        return status;
      }, {}),
      featureFlags: _featureFlags.FEATURE_FLAGS,
      currentView: this.currentView,
      timestamp: new Date().toISOString()
    };
  }
 
  /**
   * Show a message to the user
   */
  showMessage(message) {
    let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
    this.logger.debug(`Showing message: ${message}`, {
      type
    });
    // This is a placeholder for a more robust notification system
    // For now, we can use the settings status display as a general message area
    this.showSettingsStatus(message, type);
  }
}
 
// Initialize and start the application
const app = new App();
 
// Global app reference for debugging
window.app = app;
 
// Expose enableToolAfterDisclaimer function globally for modal access
window.enableToolAfterDisclaimer = () => {
  if (window.app && typeof window.app.enableToolAfterDisclaimer === 'function') {
    window.app.enableToolAfterDisclaimer();
  } else {
    window.logger?.warn('App not available or enableToolAfterDisclaimer method not found') || console.warn('App not available or enableToolAfterDisclaimer method not found');
  }
};
 
// Expose loading functions for testing
window.testLoading = {
  show: (title, message) => {
    if (window.app) {
      window.app.showModalLoading(title, message);
    }
  },
  hide: () => {
    if (window.app) {
      window.app.hideModalLoading();
    }
  },
  testSequence: () => {
    if (window.app) {
      window.logger?.info('🔄 Testing loading sequence...') || console.log('🔄 Testing loading sequence...');
      window.app.showModalLoading('Step 1', 'Testing loading overlay...');
      setTimeout(() => {
        window.app.showModalLoading('Step 2', 'Updating message...');
        setTimeout(() => {
          window.app.showModalLoading('Step 3', 'Almost done...');
          setTimeout(() => {
            window.app.hideModalLoading();
            window.logger?.info('🔄 Loading test completed') || console.log('🔄 Loading test completed');
          }, 1500);
        }, 1500);
      }, 1500);
    }
  }
};
 
// Start the application when DOM is ready
document.addEventListener('DOMContentLoaded', async () => {
  try {
    await app.init();
    window.logger?.info('🚀 PingOne Import Tool v6.5.1.1 initialized successfully') || console.log('🚀 PingOne Import Tool v6.5.1.1 initialized successfully');
    window.logger?.info('📊 Health Status:', app.getHealthStatus()) || console.log('📊 Health Status:', app.getHealthStatus());
  } catch (error) {
    window.logger?.error('❌ Application initialization failed:', error) || console.error('❌ Application initialization failed:', error);
  }
});
var _default = exports.default = App;
 
},{"../../public/js/modules/credentials-modal.js":44,"../../public/js/modules/disclaimer-modal.js":46,"../../public/js/modules/event-bus.js":49,"../../public/js/modules/file-handler.js":50,"../../public/js/modules/file-logger.js":51,"../../public/js/modules/history-subsystem.js":52,"../../public/js/modules/local-api-client.js":53,"../../public/js/modules/logger.js":54,"../../public/js/modules/logging-subsystem.js":55,"../../public/js/modules/pingone-client.js":57,"../../public/js/modules/population-subsystem.js":58,"../../public/js/modules/progress-subsystem.js":60,"../../public/js/modules/session-subsystem.js":62,"../../public/js/modules/settings-manager.js":63,"../../public/js/modules/settings-subsystem.js":64,"../../public/js/modules/token-alert-modal.js":65,"../../public/js/modules/token-manager.js":66,"../../public/js/modules/token-refresh-handler.js":67,"../../public/js/modules/version-manager.js":69,"../../public/js/utils/utility-loader.js":75,"../shared/feature-flags.js":100,"./components/analytics-dashboard-ui.js":77,"./components/history-ui.js":78,"./components/logging-ui-enhanced.js":79,"./components/realtime-collaboration-ui.js":80,"./components/testing-hub.js":81,"./components/ui-manager.js":82,"./subsystems/advanced-realtime-subsystem.js":83,"./subsystems/analytics-dashboard-subsystem.js":84,"./subsystems/auth-management-subsystem.js":85,"./subsystems/connection-manager-subsystem.js":86,"./subsystems/enhanced-progress-subsystem.js":87,"./subsystems/enhanced-token-status-subsystem.js":88,"./subsystems/export-subsystem.js":89,"./subsystems/global-token-manager-subsystem.js":90,"./subsystems/import-subsystem.js":91,"./subsystems/navigation-subsystem.js":92,"./subsystems/operation-manager-subsystem.js":93,"./subsystems/realtime-communication-subsystem.js":94,"./subsystems/token-notification-subsystem.js":95,"./subsystems/view-management-subsystem.js":96,"./utils/browser-logging-service.js":97,"./utils/debug-logger.js":98,"@babel/runtime/helpers/interopRequireDefault":2,"socket.io-client":31}],77:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AnalyticsDashboardUI = void 0;
/**
 * Simple Analytics Dashboard UI Component
 * 
 * Provides basic analytics dashboard interface with metrics, alerts, and status
 * without complex chart dependencies for better maintainability
 */
 
class AnalyticsDashboardUI {
  constructor(eventBus, analyticsDashboardSubsystem) {
    this.eventBus = eventBus;
    this.analyticsDashboardSubsystem = analyticsDashboardSubsystem;
    this.isVisible = false;
    this.updateInterval = null;
    this.logger = this.analyticsDashboardSubsystem.logger;
    this.setupEventListeners();
  }
 
  /**
   * Initialize the analytics dashboard UI
   */
  async init() {
    this.logger.debug('Initializing Simple Analytics Dashboard UI');
    try {
      this.createDashboardHTML();
      this.setupUIEventListeners();
      this.logger.info('Simple Analytics Dashboard UI initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Simple Analytics Dashboard UI', error);
      throw error;
    }
  }
 
  /**
   * Show the analytics dashboard
   */
  show() {
    if (this.isVisible) return;
    this.isVisible = true;
    const container = document.getElementById('analytics-dashboard-container');
    if (container) {
      container.classList.remove('hidden');
      this.startRealTimeUpdates();
      this.refreshDashboard();
      this.eventBus.emit('analytics-dashboard:shown');
      this.logger.debug('Analytics dashboard shown');
    }
  }
 
  /**
   * Hide the analytics dashboard
   */
  hide() {
    if (!this.isVisible) return;
    this.isVisible = false;
    const container = document.getElementById('analytics-dashboard-container');
    if (container) {
      container.classList.add('hidden');
      this.stopRealTimeUpdates();
      this.eventBus.emit('analytics-dashboard:hidden');
      this.logger.debug('Analytics dashboard hidden');
    }
  }
 
  /**
   * Toggle dashboard visibility
   */
  toggle() {
    if (this.isVisible) {
      this.hide();
    } else {
      this.show();
    }
  }
 
  /**
   * Create the dashboard HTML structure
   */
  createDashboardHTML() {
    const container = document.getElementById('analytics-view');
    if (!container) {
      this.logger.error('Analytics view container (#analytics-view) not found.');
      return;
    }
    const dashboardHTML = `
            <div id="analytics-dashboard-container" class="analytics-dashboard-container hidden">
                <div class="dashboard-content">
                    <!-- Header -->
                    <div class="dashboard-header">
                        <div class="dashboard-title">
                            <h2><i class="fas fa-chart-line"></i> Analytics Dashboard</h2>
                            <div class="dashboard-subtitle">Comprehensive real-time system metrics and performance overview</div>
                        </div>
                        <div class="dashboard-controls">
                            <div class="refresh-controls">
                                <span class="last-updated" id="last-updated">Last updated: Loading...</span>
                                <button id="refresh-dashboard" class="btn btn-outline-primary btn-sm ms-2">
                                    <i class="fas fa-sync-alt"></i> Refresh
                                </button>
                                <button id="close-analytics-dashboard" class="btn btn-outline-secondary btn-sm ms-2">
                                    <i class="fas fa-times"></i> Close
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- System Overview Cards -->
                    <div class="overview-section">
                        <div class="overview-cards">
                            <div class="overview-card">
                                <div class="card-icon"><i class="fas fa-clock"></i></div>
                                <div class="card-content">
                                    <div class="card-title">Current Time</div>
                                    <div class="card-value" id="current-time">Loading...</div>
                                    <div class="card-subtitle" id="timezone">Loading...</div>
                                </div>
                            </div>
                            <div class="overview-card">
                                <div class="card-icon"><i class="fas fa-stopwatch"></i></div>
                                <div class="card-content">
                                    <div class="card-title">Session Duration</div>
                                    <div class="card-value" id="session-duration">Loading...</div>
                                    <div class="card-subtitle" id="session-start">Loading...</div>
                                </div>
                            </div>
                            <div class="overview-card">
                                <div class="card-icon"><i class="fas fa-memory"></i></div>
                                <div class="card-content">
                                    <div class="card-title">Memory Usage</div>
                                    <div class="card-value" id="memory-usage">Loading...</div>
                                    <div class="card-subtitle" id="memory-details">Loading...</div>
                                </div>
                            </div>
                            <div class="overview-card">
                                <div class="card-icon"><i class="fas fa-microchip"></i></div>
                                <div class="card-content">
                                    <div class="card-title">CPU Usage</div>
                                    <div class="card-value" id="cpu-usage">Loading...</div>
                                    <div class="card-subtitle" id="cpu-details">Loading...</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Detailed Metrics Section -->
                    <div class="metrics-section">
                        <div class="metrics-grid">
                            <!-- System Metrics -->
                            <div class="metrics-card">
                                <div class="metrics-header">
                                    <h3><i class="fas fa-desktop"></i> System Metrics</h3>
                                </div>
                                <div class="metrics-content">
                                    <div class="metric-row">
                                        <span class="metric-label">Browser:</span>
                                        <span class="metric-value" id="browser-info">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Platform:</span>
                                        <span class="metric-value" id="platform-info">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Screen Resolution:</span>
                                        <span class="metric-value" id="screen-resolution">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Viewport Size:</span>
                                        <span class="metric-value" id="viewport-size">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Hardware Concurrency:</span>
                                        <span class="metric-value" id="hardware-concurrency">Loading...</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Performance Metrics -->
                            <div class="metrics-card">
                                <div class="metrics-header">
                                    <h3><i class="fas fa-tachometer-alt"></i> Performance Metrics</h3>
                                </div>
                                <div class="metrics-content">
                                    <div class="metric-row">
                                        <span class="metric-label">Page Load Time:</span>
                                        <span class="metric-value" id="page-load-time">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">DOM Content Loaded:</span>
                                        <span class="metric-value" id="dom-content-loaded">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">First Paint:</span>
                                        <span class="metric-value" id="first-paint">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Resources Loaded:</span>
                                        <span class="metric-value" id="resources-loaded">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">DOM Elements:</span>
                                        <span class="metric-value" id="dom-elements">Loading...</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Network & Connection -->
                            <div class="metrics-card">
                                <div class="metrics-header">
                                    <h3><i class="fas fa-wifi"></i> Network & Connection</h3>
                                </div>
                                <div class="metrics-content">
                                    <div class="metric-row">
                                        <span class="metric-label">Connection Type:</span>
                                        <span class="metric-value" id="connection-type">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Downlink Speed:</span>
                                        <span class="metric-value" id="downlink-speed">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">RTT:</span>
                                        <span class="metric-value" id="rtt">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Online Status:</span>
                                        <span class="metric-value" id="online-status">Loading...</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Storage & Resources -->
                            <div class="metrics-card">
                                <div class="metrics-header">
                                    <h3><i class="fas fa-database"></i> Storage & Resources</h3>
                                </div>
                                <div class="metrics-content">
                                    <div class="metric-row">
                                        <span class="metric-label">Local Storage:</span>
                                        <span class="metric-value" id="local-storage">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Session Storage:</span>
                                        <span class="metric-value" id="session-storage">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Color Depth:</span>
                                        <span class="metric-value" id="color-depth">Loading...</span>
                                    </div>
                                    <div class="metric-row">
                                        <span class="metric-label">Pixel Ratio:</span>
                                        <span class="metric-value" id="pixel-ratio">Loading...</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Activity and Alerts Section -->
                    <div class="activity-section">
                        <div class="activity-grid">
                            <!-- Recent Activity -->
                            <div class="activity-card">
                                <div class="activity-header">
                                    <h3><i class="fas fa-history"></i> Recent Activity</h3>
                                    <button id="refresh-activity" class="btn btn-outline-primary btn-sm">
                                        <i class="fas fa-sync-alt"></i>
                                    </button>
                                </div>
                                <div class="activity-content" id="activity-list">
                                    <div class="loading-placeholder">Loading recent activity...</div>
                                </div>
                            </div>
                            
                            <!-- System Alerts -->
                            <div class="alerts-card">
                                <div class="alerts-header">
                                    <h3><i class="fas fa-exclamation-triangle"></i> System Alerts</h3>
                                    <button id="clear-alerts" class="btn btn-outline-secondary btn-sm">
                                        <i class="fas fa-trash"></i> Clear
                                    </button>
                                </div>
                                <div class="alerts-content" id="alerts-container">
                                    <div class="no-alerts">
                                        <i class="fas fa-check-circle"></i>
                                        <span>No active alerts - All systems operational</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Summary Cards -->
                    <div class="summary-section">
                        <div class="summary-cards" id="summary-cards">
                            <!-- Dynamic summary cards will be inserted here -->
                        </div>
                    </div>
                    
                    <!-- Simple Metrics Display -->
                    <div class="charts-section">
                        <div class="charts-grid">
                            <div class="chart-container">
                                <div class="chart-header">
                                    <h3>System Status</h3>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="system-status-display" class="simple-metrics-display">
                                        <div class="metric-row">
                                            <span class="metric-label">CPU Usage:</span>
                                            <div class="metric-bar">
                                                <div class="metric-fill" id="cpu-fill" style="width: 0%"></div>
                                                <span class="metric-value" id="cpu-value">0%</span>
                                            </div>
                                        </div>
                                        <div class="metric-row">
                                            <span class="metric-label">Memory Usage:</span>
                                            <div class="metric-bar">
                                                <div class="metric-fill" id="memory-fill" style="width: 0%"></div>
                                                <span class="metric-value" id="memory-value">0%</span>
                                            </div>
                                        </div>
                                        <div class="metric-row">
                                            <span class="metric-label">Active Sessions:</span>
                                            <div class="metric-display">
                                                <span class="metric-value" id="sessions-value">0</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="chart-container">
                                <div class="chart-header">
                                    <h3>Operation Summary</h3>
                                </div>
                                <div class="chart-wrapper">
                                    <div id="operation-summary-display" class="simple-metrics-display">
                                        <div class="metric-row">
                                            <span class="metric-label">Total Operations:</span>
                                            <div class="metric-display">
                                                <span class="metric-value" id="total-ops-value">0</span>
                                            </div>
                                        </div>
                                        <div class="metric-row">
                                            <span class="metric-label">Success Rate:</span>
                                            <div class="metric-bar success-bar">
                                                <div class="metric-fill" id="success-fill" style="width: 0%"></div>
                                                <span class="metric-value" id="success-value">0%</span>
                                            </div>
                                        </div>
                                        <div class="metric-row">
                                            <span class="metric-label">Avg Response Time:</span>
                                            <div class="metric-display">
                                                <span class="metric-value" id="response-time-value">0ms</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Alerts -->
                    <div class="alerts-section">
                        <div class="section-header">
                            <h3><i class="fas fa-exclamation-triangle"></i> Active Alerts</h3>
                            <button id="clear-all-alerts" class="btn btn-outline-danger btn-sm">
                                <i class="fas fa-trash"></i> Clear All
                            </button>
                        </div>
                        <div class="alerts-container" id="alerts-container">
                            <div class="no-alerts">
                                <i class="fas fa-check-circle"></i>
                                <span>No active alerts - All systems operational</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Recent Activity -->
                    <div class="metrics-section">
                        <div class="section-header">
                            <h3><i class="fas fa-list"></i> Recent Activity</h3>
                            <button id="refresh-activity" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                        </div>
                        <div class="activity-list" id="activity-list">
                            <div class="no-data">No recent activity</div>
                        </div>
                    </div>
                </div>
            </div>
        `;
 
    // Insert dashboard HTML into the page
    document.body.insertAdjacentHTML('beforeend', dashboardHTML);
    this.logger.debug('Simple analytics dashboard HTML created');
  }
 
  /**
   * Set up UI event listeners
   */
  setupUIEventListeners() {
    // Close dashboard
    document.getElementById('close-analytics-dashboard')?.addEventListener('click', () => {
      this.hide();
    });
 
    // Refresh dashboard
    document.getElementById('refresh-dashboard')?.addEventListener('click', () => {
      this.refreshDashboard();
    });
 
    // Clear all alerts
    document.getElementById('clear-all-alerts')?.addEventListener('click', () => {
      this.clearAllAlerts();
    });
 
    // Refresh activity
    document.getElementById('refresh-activity')?.addEventListener('click', () => {
      this.refreshActivity();
    });
 
    // Close on background click
    document.getElementById('analytics-dashboard-container')?.addEventListener('click', e => {
      if (e.target.id === 'analytics-dashboard-container') {
        this.hide();
      }
    });
 
    // Keyboard shortcuts
    document.addEventListener('keydown', e => {
      if (this.isVisible && e.key === 'Escape') {
        this.hide();
      }
    });
    this.logger.debug('Simple analytics dashboard UI event listeners set up');
  }
 
  /**
   * Set up EventBus listeners
   */
  setupEventListeners() {
    // Listen for analytics data updates
    this.eventBus.on('analytics:data-updated', data => {
      this.updateDashboard(data);
    });
 
    // Listen for new alerts
    this.eventBus.on('analytics:alert-created', alert => {
      this.addAlert(alert);
    });
 
    // Listen for activity updates
    this.eventBus.on('analytics:activity-updated', activity => {
      this.updateActivity(activity);
    });
    this.logger.debug('Simple analytics dashboard event listeners set up');
  }
 
  /**
   * Start real-time updates
   */
  startRealTimeUpdates() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
    }
    this.updateInterval = setInterval(() => {
      this.refreshDashboard();
    }, 5000); // Update every 5 seconds
 
    this.logger.debug('Real-time updates started');
  }
 
  /**
   * Stop real-time updates
   */
  stopRealTimeUpdates() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
      this.updateInterval = null;
    }
    this.logger.debug('Real-time updates stopped');
  }
 
  /**
   * Refresh the entire dashboard
   */
  async refreshDashboard() {
    try {
      const data = await this.analyticsDashboardSubsystem.getAnalyticsData();
      this.updateDashboard(data);
 
      // Update refresh button state
      const refreshBtn = document.getElementById('refresh-dashboard');
      if (refreshBtn) {
        const icon = refreshBtn.querySelector('i');
        icon.classList.add('fa-spin');
        setTimeout(() => icon.classList.remove('fa-spin'), 1000);
      }
    } catch (error) {
      this.logger.error('Failed to refresh dashboard', error);
    }
  }
 
  /**
   * Update dashboard with new data
   */
  updateDashboard(data) {
    if (!data) return;
    try {
      // Update last updated timestamp
      const lastUpdatedEl = document.getElementById('last-updated');
      if (lastUpdatedEl) {
        lastUpdatedEl.textContent = `Last updated: ${new Date().toLocaleTimeString()}`;
      }
 
      // Update overview cards with time and system data
      this.updateOverviewCards(data);
 
      // Update detailed metrics sections
      this.updateSystemMetricsDetailed(data.system);
      this.updatePerformanceMetrics(data.performance);
      this.updateNetworkMetrics(data.network);
      this.updateStorageMetrics(data.browser);
 
      // Update activity and alerts
      this.updateActivity(data.activity);
      this.updateAlerts(data.alerts);
 
      // Update legacy summary cards if present
      if (data.summary) {
        this.updateSummaryCards(data.summary);
      }
      this.logger.debug('Dashboard updated successfully with comprehensive data');
    } catch (error) {
      this.logger.error('Failed to update dashboard', error);
    }
  }
 
  /**
   * Update overview cards with time, session, memory, and CPU data
   */
  updateOverviewCards(data) {
    // Current time and timezone
    const currentTimeEl = document.getElementById('current-time');
    const timezoneEl = document.getElementById('timezone');
    if (currentTimeEl && data.time) {
      currentTimeEl.textContent = data.time.currentTime || 'Unknown';
    }
    if (timezoneEl && data.time) {
      timezoneEl.textContent = data.time.timezone || 'Unknown timezone';
    }
 
    // Session duration
    const sessionDurationEl = document.getElementById('session-duration');
    const sessionStartEl = document.getElementById('session-start');
    if (sessionDurationEl && data.session) {
      sessionDurationEl.textContent = data.session.duration || 'Unknown';
    }
    if (sessionStartEl && data.session) {
      sessionStartEl.textContent = `Started: ${data.session.startTime || 'Unknown'}`;
    }
 
    // Memory usage
    const memoryUsageEl = document.getElementById('memory-usage');
    const memoryDetailsEl = document.getElementById('memory-details');
    if (memoryUsageEl && data.system && data.system.memory) {
      const memory = data.system.memory;
      memoryUsageEl.textContent = `${memory.usedPercent || 0}%`;
    }
    if (memoryDetailsEl && data.system && data.system.memory) {
      const memory = data.system.memory;
      memoryDetailsEl.textContent = `${memory.usedFormatted || '0 MB'} / ${memory.totalFormatted || '0 MB'}`;
    }
 
    // CPU usage
    const cpuUsageEl = document.getElementById('cpu-usage');
    const cpuDetailsEl = document.getElementById('cpu-details');
    if (cpuUsageEl && data.system && data.system.cpu) {
      cpuUsageEl.textContent = `${data.system.cpu.usage || 0}%`;
    }
    if (cpuDetailsEl && data.system && data.system.cpu) {
      cpuDetailsEl.textContent = data.system.cpu.details || 'Performance-based estimation';
    }
  }
 
  /**
   * Update detailed system metrics
   */
  updateSystemMetricsDetailed(system) {
    if (!system || !system.browser) return;
    const browser = system.browser;
 
    // Browser info
    const browserInfoEl = document.getElementById('browser-info');
    if (browserInfoEl) {
      browserInfoEl.textContent = browser.name || 'Unknown';
    }
 
    // Platform info
    const platformInfoEl = document.getElementById('platform-info');
    if (platformInfoEl) {
      platformInfoEl.textContent = browser.platform || 'Unknown';
    }
 
    // Screen resolution
    const screenResolutionEl = document.getElementById('screen-resolution');
    if (screenResolutionEl) {
      screenResolutionEl.textContent = browser.screenResolution || 'Unknown';
    }
 
    // Viewport size
    const viewportSizeEl = document.getElementById('viewport-size');
    if (viewportSizeEl) {
      viewportSizeEl.textContent = browser.viewportSize || 'Unknown';
    }
 
    // Hardware concurrency
    const hardwareConcurrencyEl = document.getElementById('hardware-concurrency');
    if (hardwareConcurrencyEl) {
      hardwareConcurrencyEl.textContent = browser.hardwareConcurrency || 'Unknown';
    }
  }
 
  /**
   * Update performance metrics
   */
  updatePerformanceMetrics(performance) {
    if (!performance) return;
 
    // Page load time
    const pageLoadTimeEl = document.getElementById('page-load-time');
    if (pageLoadTimeEl) {
      pageLoadTimeEl.textContent = performance.pageLoadTime || 'Unknown';
    }
 
    // DOM content loaded
    const domContentLoadedEl = document.getElementById('dom-content-loaded');
    if (domContentLoadedEl) {
      domContentLoadedEl.textContent = performance.domContentLoaded || 'Unknown';
    }
 
    // First paint
    const firstPaintEl = document.getElementById('first-paint');
    if (firstPaintEl) {
      firstPaintEl.textContent = performance.firstPaint || 'Unknown';
    }
 
    // Resources loaded
    const resourcesLoadedEl = document.getElementById('resources-loaded');
    if (resourcesLoadedEl) {
      resourcesLoadedEl.textContent = performance.resourceCount || 'Unknown';
    }
 
    // DOM elements
    const domElementsEl = document.getElementById('dom-elements');
    if (domElementsEl) {
      domElementsEl.textContent = performance.domElements || 'Unknown';
    }
  }
 
  /**
   * Update network metrics
   */
  updateNetworkMetrics(network) {
    if (!network) return;
 
    // Connection type
    const connectionTypeEl = document.getElementById('connection-type');
    if (connectionTypeEl) {
      connectionTypeEl.textContent = network.effectiveType || 'Unknown';
    }
 
    // Downlink speed
    const downlinkSpeedEl = document.getElementById('downlink-speed');
    if (downlinkSpeedEl) {
      downlinkSpeedEl.textContent = network.downlink ? `${network.downlink} Mbps` : 'Unknown';
    }
 
    // RTT
    const rttEl = document.getElementById('rtt');
    if (rttEl) {
      rttEl.textContent = network.rtt ? `${network.rtt} ms` : 'Unknown';
    }
 
    // Online status
    const onlineStatusEl = document.getElementById('online-status');
    if (onlineStatusEl) {
      onlineStatusEl.textContent = network.online ? 'Online' : 'Offline';
      onlineStatusEl.className = `metric-value ${network.online ? 'status-online' : 'status-offline'}`;
    }
  }
 
  /**
   * Update storage and browser metrics
   */
  updateStorageMetrics(browser) {
    if (!browser) return;
 
    // Local storage
    const localStorageEl = document.getElementById('local-storage');
    if (localStorageEl) {
      localStorageEl.textContent = browser.localStorage || 'Unknown';
    }
 
    // Session storage
    const sessionStorageEl = document.getElementById('session-storage');
    if (sessionStorageEl) {
      sessionStorageEl.textContent = browser.sessionStorage || 'Unknown';
    }
 
    // Color depth
    const colorDepthEl = document.getElementById('color-depth');
    if (colorDepthEl) {
      colorDepthEl.textContent = browser.colorDepth || 'Unknown';
    }
 
    // Pixel ratio
    const pixelRatioEl = document.getElementById('pixel-ratio');
    if (pixelRatioEl) {
      pixelRatioEl.textContent = browser.pixelRatio || 'Unknown';
    }
  }
  updateSummaryCards(summary) {
    const container = document.getElementById('summary-cards');
    if (!container) return;
    const cards = [{
      icon: 'fas fa-users',
      iconClass: 'info',
      value: summary.totalOperations || 0,
      label: 'Total Operations',
      change: summary.operationsChange || '+0%'
    }, {
      icon: 'fas fa-check-circle',
      iconClass: 'success',
      value: summary.successRate || '0%',
      label: 'Success Rate',
      change: summary.successRateChange || '+0%'
    }, {
      icon: 'fas fa-clock',
      iconClass: 'warning',
      value: summary.avgResponseTime || '0ms',
      label: 'Avg Response Time',
      change: summary.responseTimeChange || '+0%'
    }, {
      icon: 'fas fa-exclamation-triangle',
      iconClass: 'warning',
      value: summary.activeAlerts || 0,
      label: 'Active Alerts',
      change: summary.alertsChange || '+0'
    }];
    container.innerHTML = cards.map(card => `
            <div class="summary-card">
                <div class="card-icon ${card.iconClass}">
                    <i class="${card.icon}"></i>
                </div>
                <div class="card-content">
                    <div class="card-value">${card.value}</div>
                    <div class="card-label">${card.label}</div>
                    <div class="card-change ${card.change.startsWith('-') ? 'negative' : ''}">${card.change}</div>
                </div>
            </div>
        `).join('');
  }
 
  /**
   * Update system metrics display
   */
  updateSystemMetrics(system) {
    // Update CPU usage
    const cpuFill = document.getElementById('cpu-fill');
    const cpuValue = document.getElementById('cpu-value');
    if (cpuFill && cpuValue) {
      const cpu = system.cpuUsage || 0;
      cpuFill.style.width = `${cpu}%`;
      cpuValue.textContent = `${cpu}%`;
      cpuFill.className = `metric-fill ${cpu > 80 ? 'danger' : cpu > 60 ? 'warning' : 'success'}`;
    }
 
    // Update Memory usage
    const memoryFill = document.getElementById('memory-fill');
    const memoryValue = document.getElementById('memory-value');
    if (memoryFill && memoryValue) {
      const memory = system.memoryUsage || 0;
      memoryFill.style.width = `${memory}%`;
      memoryValue.textContent = `${memory}%`;
      memoryFill.className = `metric-fill ${memory > 80 ? 'danger' : memory > 60 ? 'warning' : 'success'}`;
    }
 
    // Update Active sessions
    const sessionsValue = document.getElementById('sessions-value');
    if (sessionsValue) {
      sessionsValue.textContent = system.activeSessions || 0;
    }
  }
 
  /**
   * Update operation metrics display
   */
  updateOperationMetrics(operations) {
    // Update total operations
    const totalOpsValue = document.getElementById('total-ops-value');
    if (totalOpsValue) {
      totalOpsValue.textContent = operations.totalOperations || 0;
    }
 
    // Update success rate
    const successFill = document.getElementById('success-fill');
    const successValue = document.getElementById('success-value');
    if (successFill && successValue) {
      const successRate = operations.successRate || 0;
      successFill.style.width = `${successRate}%`;
      successValue.textContent = `${successRate}%`;
    }
 
    // Update response time
    const responseTimeValue = document.getElementById('response-time-value');
    if (responseTimeValue) {
      responseTimeValue.textContent = operations.avgResponseTime || '0ms';
    }
  }
 
  /**
   * Update alerts
   */
  updateAlerts(alerts) {
    const container = document.getElementById('alerts-container');
    if (!container) return;
    if (!alerts || alerts.length === 0) {
      container.innerHTML = `
                <div class="no-alerts">
                    <i class="fas fa-check-circle"></i>
                    <span>No active alerts - All systems operational</span>
                </div>
            `;
      return;
    }
    container.innerHTML = alerts.map(alert => `
            <div class="alert-item ${alert.severity || 'info'}" data-alert-id="${alert.id}">
                <div class="alert-icon">
                    <i class="fas fa-${this.getAlertIcon(alert.severity)}"></i>
                </div>
                <div class="alert-content">
                    <div class="alert-message">${alert.message}</div>
                    <div class="alert-time">${this.formatTime(alert.timestamp)}</div>
                </div>
                <button class="alert-dismiss" onclick="this.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `).join('');
  }
 
  /**
   * Add a new alert
   */
  addAlert(alert) {
    const container = document.getElementById('alerts-container');
    if (!container) return;
 
    // Remove "no alerts" message if present
    const noAlerts = container.querySelector('.no-alerts');
    if (noAlerts) {
      noAlerts.remove();
    }
    const alertHTML = `
            <div class="alert-item ${alert.severity || 'info'}" data-alert-id="${alert.id}">
                <div class="alert-icon">
                    <i class="fas fa-${this.getAlertIcon(alert.severity)}"></i>
                </div>
                <div class="alert-content">
                    <div class="alert-message">${alert.message}</div>
                    <div class="alert-time">${this.formatTime(alert.timestamp)}</div>
                </div>
                <button class="alert-dismiss" onclick="this.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
    container.insertAdjacentHTML('afterbegin', alertHTML);
  }
 
  /**
   * Update activity list
   */
  updateActivity(activities) {
    const container = document.getElementById('activity-list');
    if (!container) return;
    if (!activities || activities.length === 0) {
      container.innerHTML = '<div class="no-data">No recent activity</div>';
      return;
    }
    container.innerHTML = activities.slice(0, 10).map(activity => `
            <div class="activity-item">
                <div class="activity-icon ${activity.type || 'info'}">
                    <i class="fas fa-${this.getActivityIcon(activity.type)}"></i>
                </div>
                <div class="activity-content">
                    <div class="activity-message">${activity.message}</div>
                    <div class="activity-time">${this.formatTime(activity.timestamp)}</div>
                </div>
            </div>
        `).join('');
  }
 
  /**
   * Clear all alerts
   */
  clearAllAlerts() {
    const container = document.getElementById('alerts-container');
    if (container) {
      container.innerHTML = `
                <div class="no-alerts">
                    <i class="fas fa-check-circle"></i>
                    <span>No active alerts - All systems operational</span>
                </div>
            `;
    }
    this.eventBus.emit('analytics:alerts-cleared');
    this.logger.debug('All alerts cleared');
  }
 
  /**
   * Refresh activity
   */
  refreshActivity() {
    this.logger.debug('Refreshing activity');
    this.eventBus.emit('analytics:activity-refresh-requested');
 
    // Show refresh in progress
    const refreshBtn = document.getElementById('refresh-activity');
    if (refreshBtn) {
      const icon = refreshBtn.querySelector('i');
      icon.classList.add('fa-spin');
      setTimeout(() => icon.classList.remove('fa-spin'), 1000);
    }
  }
 
  /**
   * Get appropriate icon for alert severity
   */
  getAlertIcon(severity) {
    switch (severity) {
      case 'error':
        return 'exclamation-circle';
      case 'warning':
        return 'exclamation-triangle';
      case 'info':
        return 'info-circle';
      default:
        return 'info-circle';
    }
  }
 
  /**
   * Get appropriate icon for activity type
   */
  getActivityIcon(type) {
    switch (type) {
      case 'import':
        return 'upload';
      case 'export':
        return 'download';
      case 'delete':
        return 'trash';
      case 'modify':
        return 'edit';
      case 'error':
        return 'exclamation-circle';
      case 'success':
        return 'check-circle';
      default:
        return 'info-circle';
    }
  }
 
  /**
   * Format timestamp for display
   */
  formatTime(timestamp) {
    if (!timestamp) return 'Unknown';
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    if (diff < 60000) return 'Just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return date.toLocaleDateString();
  }
 
  /**
   * Cleanup resources
   */
  destroy() {
    this.stopRealTimeUpdates();
 
    // Remove dashboard HTML
    const container = document.getElementById('analytics-dashboard-container');
    if (container) {
      container.remove();
    }
    this.logger.debug('Simple Analytics Dashboard UI destroyed');
  }
}
exports.AnalyticsDashboardUI = AnalyticsDashboardUI;
 
},{}],78:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.HistoryUIComponent = void 0;
/**
 * History UI Component
 * Modern history management interface integrated with HistorySubsystem
 * Provides comprehensive history viewing, filtering, and management capabilities
 */
 
class HistoryUIComponent {
  constructor(historySubsystem, eventBus, logger) {
    this.historySubsystem = historySubsystem;
    this.eventBus = eventBus;
    this.logger = logger;
 
    // UI state
    this.currentHistory = [];
    this.filteredHistory = [];
    this.currentPage = 1;
    this.itemsPerPage = 20;
    this.isLoading = false;
 
    // Filter state
    this.currentFilters = {
      category: '',
      status: '',
      dateFrom: '',
      dateTo: '',
      search: ''
    };
 
    // UI elements cache
    this.elements = {};
    this.filterTimeout = null;
    this.logger.debug('HistoryUIComponent initialized');
  }
 
  /**
   * Initialize the History UI Component
   */
  async init() {
    try {
      this.logger.info('Initializing HistoryUIComponent');
 
      // Create the UI container
      this.createUI();
 
      // Cache DOM elements
      this.cacheElements();
 
      // Setup event listeners
      this.setupEventListeners();
 
      // Setup filter listeners
      this.setupFilterListeners();
 
      // Load initial history
      await this.loadHistory();
      this.logger.info('HistoryUIComponent initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize HistoryUIComponent:', error);
      throw error;
    }
  }
 
  /**
   * Create the UI structure
   */
  createUI() {
    const container = document.getElementById('history-view');
    if (!container) {
      this.logger.error('History view container not found');
      return;
    }
    container.innerHTML = `
            <div class="history-container">
                <!-- Header -->
                <div class="history-header">
                    <h2><i class="fas fa-history"></i> Operation History</h2>
                    <p>Track and manage all operations</p>
                </div>
 
                <!-- Statistics Cards -->
                <div class="history-stats">
                    <div class="stat-card">
                        <div class="stat-value" id="total-operations">0</div>
                        <div class="stat-label">Total Operations</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="successful-operations">0</div>
                        <div class="stat-label">Successful</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="failed-operations">0</div>
                        <div class="stat-label">Failed</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="success-rate">0%</div>
                        <div class="stat-label">Success Rate</div>
                    </div>
                </div>
 
                <!-- Controls -->
                <div class="history-controls">
                    <div class="history-filters">
                        <div class="filter-group">
                            <label for="category-filter">Category</label>
                            <select id="category-filter">
                                <option value="">All Categories</option>
                                <option value="import">Import</option>
                                <option value="export">Export</option>
                                <option value="delete">Delete</option>
                                <option value="modify">Modify</option>
                                <option value="settings">Settings</option>
                                <option value="auth">Authentication</option>
                                <option value="system">System</option>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label for="status-filter">Status</label>
                            <select id="status-filter">
                                <option value="">All Status</option>
                                <option value="started">Started</option>
                                <option value="in_progress">In Progress</option>
                                <option value="completed">Completed</option>
                                <option value="failed">Failed</option>
                                <option value="cancelled">Cancelled</option>
                                <option value="partial">Partial</option>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label for="date-from">From Date</label>
                            <input type="date" id="date-from">
                        </div>
                        
                        <div class="filter-group">
                            <label for="date-to">To Date</label>
                            <input type="date" id="date-to">
                        </div>
                        
                        <div class="filter-group search-filter">
                            <label for="history-search-filter">Search</label>
                            <input type="search" id="history-search-filter" placeholder="Search by keyword...">
                        </div>
                    </div>
                    
                    <div class="history-actions">
                        <button class="btn-modern" id="refresh-btn">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </button>
                        <button class="btn-modern" id="export-btn">
                            <i class="fas fa-download"></i> Export
                        </button>
                        <button class="btn-modern" id="clear-filters-btn">
                            <i class="fas fa-filter"></i> Clear Filters
                        </button>
                        <button class="btn-modern btn-danger" id="clear-history-btn">
                            <i class="fas fa-trash"></i> Clear History
                        </button>
                    </div>
                </div>
 
                <!-- History List -->
                <div class="history-list" id="history-list">
                    <div class="loading-state">
                        <div class="loading-spinner"></div>
                        <p>Loading history...</p>
                    </div>
                </div>
 
                <!-- Pagination -->
                <div class="history-pagination" id="pagination" style="display: none;">
                    <button id="prev-page" class="btn-modern" disabled>
                        <i class="fas fa-chevron-left"></i> Previous
                    </button>
                    <span id="pagination-info">Page 1 of 1</span>
                    <button id="next-page" class="btn-modern" disabled>
                        Next <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        `;
  }
 
  /**
   * Cache frequently used DOM elements
   */
  cacheElements() {
    this.elements = {
      historyList: document.getElementById('history-list'),
      pagination: document.getElementById('pagination'),
      categoryFilter: document.getElementById('category-filter'),
      statusFilter: document.getElementById('status-filter'),
      dateFromFilter: document.getElementById('date-from'),
      dateToFilter: document.getElementById('date-to'),
      searchFilter: document.getElementById('history-search-filter'),
      totalOperations: document.getElementById('total-operations'),
      successfulOperations: document.getElementById('successful-operations'),
      failedOperations: document.getElementById('failed-operations'),
      successRate: document.getElementById('success-rate'),
      prevPageBtn: document.getElementById('prev-page'),
      nextPageBtn: document.getElementById('next-page'),
      paginationInfo: document.getElementById('pagination-info'),
      refreshBtn: document.getElementById('refresh-btn'),
      exportBtn: document.getElementById('export-btn'),
      clearFiltersBtn: document.getElementById('clear-filters-btn'),
      clearHistoryBtn: document.getElementById('clear-history-btn')
    };
  }
 
  /**
   * Setup event listeners for real-time updates
   */
  setupEventListeners() {
    if (this.eventBus) {
      // Listen for history updates from HistorySubsystem
      this.eventBus.on('historyEntryAdded', () => {
        this.logger.debug('History entry added event received');
        this.loadHistory();
      });
      this.eventBus.on('historyEntryUpdated', () => {
        this.logger.debug('History entry updated event received');
        this.loadHistory();
      });
      this.eventBus.on('historyEntryDeleted', () => {
        this.logger.debug('History entry deleted event received');
        this.loadHistory();
      });
      this.eventBus.on('historyCleared', () => {
        this.logger.debug('History cleared event received');
        this.currentHistory = [];
        this.filteredHistory = [];
        this.displayHistory();
      });
    }
 
    // Button event listeners
    if (this.elements.refreshBtn) {
      this.elements.refreshBtn.addEventListener('click', () => this.refresh());
    }
    if (this.elements.exportBtn) {
      this.elements.exportBtn.addEventListener('click', () => this.exportHistory());
    }
    if (this.elements.clearFiltersBtn) {
      this.elements.clearFiltersBtn.addEventListener('click', () => this.clearFilters());
    }
    if (this.elements.clearHistoryBtn) {
      this.elements.clearHistoryBtn.addEventListener('click', () => this.clearHistory());
    }
 
    // Pagination event listeners
    if (this.elements.prevPageBtn) {
      this.elements.prevPageBtn.addEventListener('click', () => this.previousPage());
    }
    if (this.elements.nextPageBtn) {
      this.elements.nextPageBtn.addEventListener('click', () => this.nextPage());
    }
  }
 
  /**
   * Setup filter change listeners
   */
  setupFilterListeners() {
    const filterElements = [this.elements.categoryFilter, this.elements.statusFilter, this.elements.dateFromFilter, this.elements.dateToFilter];
    filterElements.forEach(element => {
      if (element) {
        element.addEventListener('change', () => this.applyFilters());
      }
    });
 
    // Search filter with debounce
    if (this.elements.searchFilter) {
      this.elements.searchFilter.addEventListener('input', () => this.debounceFilter());
    }
  }
 
  /**
   * Debounce filter for search input
   */
  debounceFilter() {
    if (this.filterTimeout) {
      clearTimeout(this.filterTimeout);
    }
    this.filterTimeout = setTimeout(() => this.applyFilters(), 300);
  }
 
  /**
   * Load history from HistorySubsystem
   */
  async loadHistory() {
    if (this.isLoading) return;
    try {
      this.isLoading = true;
      this.showLoadingState();
      this.logger.debug('Loading history from HistorySubsystem');
 
      // Get history from subsystem
      const historyData = await this.historySubsystem.getHistory({
        limit: 1000,
        // Load more for client-side filtering
        sortBy: 'timestamp',
        sortOrder: 'desc'
      });
      this.currentHistory = historyData.history || [];
 
      // Apply current filters
      this.applyFilters();
 
      // Update statistics
      const stats = await this.historySubsystem.getHistoryStats(this.currentHistory);
      this.updateStatistics(stats);
      this.logger.debug('History loaded successfully', {
        count: this.currentHistory.length
      });
    } catch (error) {
      this.logger.error('Failed to load history:', error);
      this.showError('Failed to load history', error.message);
    } finally {
      this.isLoading = false;
    }
  }
 
  /**
   * Apply current filters to history
   */
  applyFilters() {
    // Update filter state
    this.currentFilters = {
      category: this.elements.categoryFilter?.value || '',
      status: this.elements.statusFilter?.value || '',
      dateFrom: this.elements.dateFromFilter?.value || '',
      dateTo: this.elements.dateToFilter?.value || '',
      search: this.elements.searchFilter?.value || ''
    };
 
    // Filter history
    this.filteredHistory = this.currentHistory.filter(entry => this.matchesFilters(entry));
 
    // Reset to first page
    this.currentPage = 1;
 
    // Display filtered results
    this.displayHistory();
    this.logger.debug('Filters applied', {
      filters: this.currentFilters,
      resultCount: this.filteredHistory.length
    });
  }
 
  /**
   * Check if entry matches current filters
   */
  matchesFilters(entry) {
    // Category filter
    if (this.currentFilters.category && entry.category !== this.currentFilters.category) {
      return false;
    }
 
    // Status filter
    if (this.currentFilters.status && entry.status !== this.currentFilters.status) {
      return false;
    }
 
    // Date filters
    if (this.currentFilters.dateFrom) {
      const entryDate = new Date(entry.timestamp);
      const fromDate = new Date(this.currentFilters.dateFrom);
      if (entryDate < fromDate) {
        return false;
      }
    }
    if (this.currentFilters.dateTo) {
      const entryDate = new Date(entry.timestamp);
      const toDate = new Date(this.currentFilters.dateTo);
      toDate.setHours(23, 59, 59, 999); // End of day
      if (entryDate > toDate) {
        return false;
      }
    }
 
    // Search filter
    if (this.currentFilters.search) {
      const searchTerm = this.currentFilters.search.toLowerCase();
      const searchableText = [entry.description, entry.category, entry.status, JSON.stringify(entry.data)].join(' ').toLowerCase();
      if (!searchableText.includes(searchTerm)) {
        return false;
      }
    }
    return true;
  }
 
  /**
   * Display history entries with pagination
   */
  displayHistory() {
    if (!this.elements.historyList) return;
    if (this.filteredHistory.length === 0) {
      this.showNoHistory();
      return;
    }
 
    // Calculate pagination
    const totalPages = Math.ceil(this.filteredHistory.length / this.itemsPerPage);
    const startIndex = (this.currentPage - 1) * this.itemsPerPage;
    const endIndex = startIndex + this.itemsPerPage;
    const pageHistory = this.filteredHistory.slice(startIndex, endIndex);
 
    // Generate HTML
    let html = '';
    pageHistory.forEach(entry => {
      html += this.createHistoryEntryHTML(entry);
    });
    this.elements.historyList.innerHTML = html;
    this.updatePagination(totalPages);
  }
 
  /**
   * Create HTML for a history entry
   */
  createHistoryEntryHTML(entry) {
    const timestamp = new Date(entry.timestamp).toLocaleString();
    const duration = entry.duration ? this.formatDuration(entry.duration) : 'N/A';
    return `
            <div class="history-entry" data-id="${entry.id}">
                <div class="history-entry-header">
                    <div class="history-entry-info">
                        <div class="history-entry-title">
                            ${this.getCategoryIcon(entry.category)} ${entry.description}
                        </div>
                        <div class="history-entry-meta">
                            <span><i class="fas fa-clock"></i> ${timestamp}</span>
                            <span><i class="fas fa-tag"></i> ${entry.category}</span>
                            <span class="status-badge status-${entry.status}">${entry.status}</span>
                            ${duration !== 'N/A' ? `<span><i class="fas fa-stopwatch"></i> ${duration}</span>` : ''}
                        </div>
                    </div>
                    <div class="history-entry-actions">
                        <button class="btn-small" onclick="this.closest('.history-entry').querySelector('.history-entry-details').style.display = this.closest('.history-entry').querySelector('.history-entry-details').style.display === 'none' ? 'block' : 'none'">
                            <i class="fas fa-chevron-down"></i>
                        </button>
                    </div>
                </div>
                <div class="history-entry-details" style="display: none;">
                    ${this.createEntryDetails(entry)}
                </div>
            </div>
        `;
  }
 
  /**
   * Create details section for history entry
   */
  createEntryDetails(entry) {
    const sanitizedData = this.sanitizeDataForDisplay(entry.data);
    return `
            <div class="entry-details-content">
                <div class="detail-section">
                    <h4>Session Information</h4>
                    <p><strong>Session ID:</strong> ${entry.sessionId}</p>
                    <p><strong>Start Time:</strong> ${new Date(entry.startTime).toLocaleString()}</p>
                </div>
                <div class="detail-section">
                    <h4>Operation Data</h4>
                    <pre class="data-display">${JSON.stringify(sanitizedData, null, 2)}</pre>
                </div>
            </div>
        `;
  }
 
  /**
   * Sanitize data for display
   */
  sanitizeDataForDisplay(data) {
    if (!data || typeof data !== 'object') return data;
    const sanitized = {
      ...data
    };
    const sensitiveFields = ['password', 'token', 'secret', 'key', 'apiKey', 'clientSecret'];
    const sanitizeObject = obj => {
      Object.keys(obj).forEach(key => {
        if (sensitiveFields.some(field => key.toLowerCase().includes(field))) {
          obj[key] = '[REDACTED]';
        } else if (typeof obj[key] === 'object' && obj[key] !== null) {
          sanitizeObject(obj[key]);
        }
      });
    };
    sanitizeObject(sanitized);
    return sanitized;
  }
 
  /**
   * Get icon for category
   */
  getCategoryIcon(category) {
    const icons = {
      import: '<i class="fas fa-file-import"></i>',
      export: '<i class="fas fa-file-export"></i>',
      delete: '<i class="fas fa-trash"></i>',
      modify: '<i class="fas fa-edit"></i>',
      settings: '<i class="fas fa-cog"></i>',
      auth: '<i class="fas fa-lock"></i>',
      system: '<i class="fas fa-server"></i>'
    };
    return icons[category] || '<i class="fas fa-file"></i>';
  }
 
  /**
   * Format duration in milliseconds to readable format
   */
  formatDuration(duration) {
    if (duration < 1000) return `${duration}ms`;
    if (duration < 60000) return `${(duration / 1000).toFixed(1)}s`;
    if (duration < 3600000) return `${(duration / 60000).toFixed(1)}m`;
    return `${(duration / 3600000).toFixed(1)}h`;
  }
 
  /**
   * Update statistics display
   */
  updateStatistics(stats) {
    if (this.elements.totalOperations) {
      this.elements.totalOperations.textContent = stats.total || 0;
    }
    if (this.elements.successfulOperations) {
      this.elements.successfulOperations.textContent = stats.successful || 0;
    }
    if (this.elements.failedOperations) {
      this.elements.failedOperations.textContent = stats.failed || 0;
    }
    if (this.elements.successRate) {
      this.elements.successRate.textContent = `${stats.successRate || 0}%`;
    }
  }
 
  /**
   * Update pagination controls
   */
  updatePagination(totalPages) {
    if (!this.elements.pagination) return;
    if (totalPages <= 1) {
      this.elements.pagination.style.display = 'none';
      return;
    }
    this.elements.pagination.style.display = 'flex';
    if (this.elements.paginationInfo) {
      this.elements.paginationInfo.textContent = `Page ${this.currentPage} of ${totalPages}`;
    }
    if (this.elements.prevPageBtn) {
      this.elements.prevPageBtn.disabled = this.currentPage <= 1;
    }
    if (this.elements.nextPageBtn) {
      this.elements.nextPageBtn.disabled = this.currentPage >= totalPages;
    }
  }
 
  /**
   * Show loading state
   */
  showLoadingState() {
    if (!this.elements.historyList) return;
    this.elements.historyList.innerHTML = `
            <div class="loading-state">
                <div class="loading-spinner"></div>
                <p>Loading history...</p>
            </div>
        `;
  }
 
  /**
   * Show no history state
   */
  showNoHistory() {
    if (!this.elements.historyList) return;
    this.elements.historyList.innerHTML = `
            <div class="no-history">
                <i class="fas fa-history"></i>
                <h3>No History Found</h3>
                <p>No operations match your current filters.</p>
            </div>
        `;
    if (this.elements.pagination) {
      this.elements.pagination.style.display = 'none';
    }
  }
 
  /**
   * Show error state
   */
  showError(title, message) {
    if (!this.elements.historyList) return;
    this.elements.historyList.innerHTML = `
            <div class="error-state">
                <i class="fas fa-exclamation-triangle"></i>
                <h3>${title}</h3>
                <p>${message}</p>
                <button class="btn-modern" onclick="this.closest('.history-container').dispatchEvent(new CustomEvent('retry'))">
                    <i class="fas fa-retry"></i> Retry
                </button>
            </div>
        `;
  }
 
  /**
   * Navigate to next page
   */
  nextPage() {
    const totalPages = Math.ceil(this.filteredHistory.length / this.itemsPerPage);
    if (this.currentPage < totalPages) {
      this.currentPage++;
      this.displayHistory();
    }
  }
 
  /**
   * Navigate to previous page
   */
  previousPage() {
    if (this.currentPage > 1) {
      this.currentPage--;
      this.displayHistory();
    }
  }
 
  /**
   * Clear all filters
   */
  clearFilters() {
    if (this.elements.categoryFilter) this.elements.categoryFilter.value = '';
    if (this.elements.statusFilter) this.elements.statusFilter.value = '';
    if (this.elements.dateFromFilter) this.elements.dateFromFilter.value = '';
    if (this.elements.dateToFilter) this.elements.dateToFilter.value = '';
    if (this.elements.searchFilter) this.elements.searchFilter.value = '';
    this.applyFilters();
    this.logger.debug('Filters cleared');
  }
 
  /**
   * Export history using HistorySubsystem
   */
  async exportHistory() {
    try {
      this.logger.info('Exporting history');
      await this.historySubsystem.exportHistory({
        format: 'csv',
        filtered: true,
        filters: this.currentFilters
      });
      this.logger.info('History exported successfully');
    } catch (error) {
      this.logger.error('Failed to export history:', error);
      alert('Failed to export history: ' + error.message);
    }
  }
 
  /**
   * Clear all history using HistorySubsystem
   */
  async clearHistory() {
    if (!confirm('Are you sure you want to clear all history? This action cannot be undone.')) {
      return;
    }
    try {
      this.logger.info('Clearing all history');
      await this.historySubsystem.clearHistory();
      this.logger.info('History cleared successfully');
 
      // Reload history to reflect changes
      await this.loadHistory();
    } catch (error) {
      this.logger.error('Failed to clear history:', error);
      alert('Failed to clear history: ' + error.message);
    }
  }
 
  /**
   * Refresh history data
   */
  async refresh() {
    this.logger.debug('Refreshing history');
    await this.loadHistory();
  }
 
  /**
   * Destroy the UI and cleanup
   */
  destroy() {
    // Clear timeouts
    if (this.filterTimeout) {
      clearTimeout(this.filterTimeout);
    }
 
    // Remove event listeners
    if (this.eventBus) {
      this.eventBus.off('historyEntryAdded');
      this.eventBus.off('historyEntryUpdated');
      this.eventBus.off('historyEntryDeleted');
      this.eventBus.off('historyCleared');
    }
    this.logger.debug('HistoryUIComponent destroyed');
  }
}
exports.HistoryUIComponent = HistoryUIComponent;
var _default = exports.default = HistoryUIComponent;
 
},{}],79:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.EnhancedLoggingUIComponent = void 0;
/**
 * Enhanced Logging UI Component
 * Modern logging interface with bolder colors, improved arrow styling, and enhanced log type filters
 * Integrated with LoggingSubsystem for comprehensive log viewing and management
 */
 
class EnhancedLoggingUIComponent {
  constructor(loggingSubsystem, eventBus, logger) {
    this.loggingSubsystem = loggingSubsystem;
    this.eventBus = eventBus;
    this.logger = logger;
 
    // UI state
    this.currentLogs = [];
    this.filteredLogs = [];
    this.currentPage = 1;
    this.itemsPerPage = 50;
    this.isLoading = false;
    this.isAutoRefresh = true;
    this.refreshInterval = null;
 
    // Filter state
    this.currentFilters = {
      level: 'all',
      category: 'all',
      dateFrom: '',
      dateTo: '',
      search: ''
    };
 
    // Log type counts for filters
    this.logTypeCounts = {
      all: 0,
      error: 0,
      warn: 0,
      info: 0,
      debug: 0,
      trace: 0
    };
 
    // UI elements cache
    this.elements = {};
    this.filterTimeout = null;
 
    // Make available globally for onclick handlers
    window.enhancedLoggingUI = this;
    this.logger.debug('EnhancedLoggingUIComponent initialized');
  }
 
  /**
   * Initialize the Enhanced Logging UI Component
   */
  async init() {
    try {
      this.logger.info('Initializing EnhancedLoggingUIComponent');
 
      // Create the UI container
      this.createUI();
 
      // Cache DOM elements
      this.cacheElements();
 
      // Setup event listeners
      this.setupEventListeners();
 
      // Setup filter listeners
      this.setupFilterListeners();
 
      // Load initial logs
      await this.loadLogs();
 
      // Start auto-refresh
      this.startAutoRefresh();
      this.logger.info('EnhancedLoggingUIComponent initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize EnhancedLoggingUIComponent:', error);
      throw error;
    }
  }
 
  /**
   * Create the enhanced UI structure with log type filters
   */
  createUI() {
    const container = document.getElementById('logs-view');
    if (!container) {
      this.logger.error('Logs view container not found');
      return;
    }
    container.innerHTML = `
            <div class="logging-container">
                <!-- Header -->
                <div class="logging-header">
                    <h2><i class="fas fa-file-alt"></i> Enhanced System Logs</h2>
                    <p>Monitor and analyze system activity with enhanced filtering and visualization</p>
                </div>
 
                <!-- Statistics Cards -->
                <div class="logging-stats">
                    <div class="stat-card">
                        <div class="stat-value" id="total-logs">0</div>
                        <div class="stat-label">Total Logs</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="error-logs">0</div>
                        <div class="stat-label">Errors</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="warning-logs">0</div>
                        <div class="stat-label">Warnings</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" id="info-logs">0</div>
                        <div class="stat-label">Info</div>
                    </div>
                </div>
 
                <!-- Enhanced Log Type Filters -->
                <div class="log-type-filters">
                    <button class="log-type-filter active" data-type="all">All Logs <span class="log-count" id="count-all">0</span></button>
                    <button class="log-type-filter" data-type="error">Errors <span class="log-count" id="count-error">0</span></button>
                    <button class="log-type-filter" data-type="warn">Warnings <span class="log-count" id="count-warn">0</span></button>
                    <button class="log-type-filter" data-type="info">Info <span class="log-count" id="count-info">0</span></button>
                    <button class="log-type-filter" data-type="debug">Debug <span class="log-count" id="count-debug">0</span></button>
                    <button class="log-type-filter" data-type="trace">Trace <span class="log-count" id="count-trace">0</span></button>
                </div>
 
                <!-- Filter and Action Controls -->
                <div class="logging-controls">
                    <div class="filter-group">
                        <label for="log-category-filter">Category</label>
                        <select id="log-category-filter">
                            <option value="all">All</option>
                            <option value="general">General</option>
                            <option value="auth">Authentication</option>
                            <option value="api">API</option>
                            <option value="import">Import</option>
                            <option value="export">Export</option>
                            <option value="system">System</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label for="log-date-from">From</label>
                        <input type="date" id="log-date-from">
                    </div>
                    <div class="filter-group">
                        <label for="log-date-to">To</label>
                        <input type="date" id="log-date-to">
                    </div>
                    <div class="filter-group search-filter">
                        <label for="log-search-filter">Search</label>
                        <input type="text" id="log-search-filter" placeholder="Search logs...">
                    </div>
                    <div class="action-group">
                        <button id="clear-filters-btn" class="btn btn-secondary"><i class="fas fa-times"></i> Clear</button>
                        <button id="export-logs-btn" class="btn btn-primary"><i class="fas fa-download"></i> Export</button>
                        <button id="clear-logs-btn" class="btn btn-danger"><i class="fas fa-trash"></i> Clear Logs</button>
                        <button id="refresh-logs-btn" class="btn btn-primary"><i class="fas fa-sync"></i> Refresh</button>
                    </div>
                </div>
 
                <!-- Logging List -->
                <div id="logging-list-container" class="logging-list-container">
                    <!-- Loading state -->
                    <div id="logging-loading" class="loading-overlay" style="display: none;">
                        <div class="spinner"></div>
                        <p>Loading logs...</p>
                    </div>
                    <!-- No logs state -->
                    <div id="no-logs-message" class="no-logs-message" style="display: none;">
                        <i class="fas fa-info-circle"></i>
                        <p>No logs found. Try adjusting your filters.</p>
                    </div>
                    <!-- Error state -->
                    <div id="logging-error" class="error-message" style="display: none;">
                        <i class="fas fa-exclamation-triangle"></i>
                        <h4 id="logging-error-title">Error</h4>
                        <p id="logging-error-message">An unexpected error occurred.</p>
                    </div>
                    <ul id="logging-list"></ul>
                </div>
 
                <!-- Pagination -->
                <div class="logging-pagination">
                    <button id="prev-page-btn" class="btn btn-secondary" disabled><i class="fas fa-arrow-left"></i> Previous</button>
                    <span id="page-info">Page 1 of 1</span>
                    <button id="next-page-btn" class="btn btn-secondary" disabled><i class="fas fa-arrow-right"></i> Next</button>
                </div>
            </div>
        `;
  }
 
  /**
   * Cache frequently used DOM elements
   */
  cacheElements() {
    this.elements.container = document.getElementById('logs-view');
    this.elements.loggingList = this.elements.container.querySelector('#logging-list');
    this.elements.loadingOverlay = this.elements.container.querySelector('#logging-loading');
    this.elements.noLogsMessage = this.elements.container.querySelector('#no-logs-message');
    this.elements.errorMessage = this.elements.container.querySelector('#logging-error');
    this.elements.errorTitle = this.elements.container.querySelector('#logging-error-title');
    this.elements.errorMessageText = this.elements.container.querySelector('#logging-error-message');
 
    // Stats
    this.elements.totalLogs = this.elements.container.querySelector('#total-logs');
    this.elements.errorLogs = this.elements.container.querySelector('#error-logs');
    this.elements.warningLogs = this.elements.container.querySelector('#warning-logs');
    this.elements.infoLogs = this.elements.container.querySelector('#info-logs');
 
    // Filters
    this.elements.categoryFilter = this.elements.container.querySelector('#log-category-filter');
    this.elements.dateFromFilter = this.elements.container.querySelector('#log-date-from');
    this.elements.dateToFilter = this.elements.container.querySelector('#log-date-to');
    this.elements.searchFilter = this.elements.container.querySelector('#log-search-filter');
 
    // Pagination
    this.elements.prevPageBtn = this.elements.container.querySelector('#prev-page-btn');
    this.elements.nextPageBtn = this.elements.container.querySelector('#next-page-btn');
    this.elements.pageInfo = this.elements.container.querySelector('#page-info');
  }
 
  /**
   * Setup event listeners for real-time updates
   */
  setupEventListeners() {
    // EventBus listeners
    this.eventBus.on('logEntryAdded', this.handleNewLogEntry.bind(this));
    this.eventBus.on('logsCleared', this.handleLogsCleared.bind(this));
 
    // Pagination listeners
    this.elements.prevPageBtn.addEventListener('click', () => this.previousPage());
    this.elements.nextPageBtn.addEventListener('click', () => this.nextPage());
 
    // Action listeners
    const clearFiltersBtn = this.elements.container.querySelector('#clear-filters-btn');
    clearFiltersBtn.addEventListener('click', () => this.clearFilters());
    const exportLogsBtn = this.elements.container.querySelector('#export-logs-btn');
    exportLogsBtn.addEventListener('click', () => this.exportLogs());
    const clearLogsBtn = this.elements.container.querySelector('#clear-logs-btn');
    clearLogsBtn.addEventListener('click', () => this.clearLogs());
    const refreshLogsBtn = this.elements.container.querySelector('#refresh-logs-btn');
    refreshLogsBtn.addEventListener('click', () => this.refresh());
 
    // Log type filter listeners
    const logTypeFilters = this.elements.container.querySelectorAll('.log-type-filter');
    logTypeFilters.forEach(button => {
      button.addEventListener('click', () => {
        this.filterByType(button.dataset.type);
      });
    });
  }
 
  /**
   * Setup filter change listeners
   */
  setupFilterListeners() {
    this.elements.categoryFilter.addEventListener('change', () => {
      this.currentFilters.category = this.elements.categoryFilter.value;
      this.applyFilters();
    });
    this.elements.dateFromFilter.addEventListener('change', () => {
      this.currentFilters.dateFrom = this.elements.dateFromFilter.value;
      this.applyFilters();
    });
    this.elements.dateToFilter.addEventListener('change', () => {
      this.currentFilters.dateTo = this.elements.dateToFilter.value;
      this.applyFilters();
    });
    this.elements.searchFilter.addEventListener('input', this.debounceFilter.bind(this));
  }
 
  /**
   * Debounce filter for search input
   */
  debounceFilter() {
    clearTimeout(this.filterTimeout);
    this.filterTimeout = setTimeout(() => {
      this.currentFilters.search = this.elements.searchFilter.value;
      this.applyFilters();
    }, 300);
  }
 
  /**
   * Filter logs by type (enhanced log type filters)
   */
  filterByType(type) {
    this.currentFilters.level = type;
    this.applyFilters();
 
    // Update active class on filter buttons
    const logTypeFilters = this.elements.container.querySelectorAll('.log-type-filter');
    logTypeFilters.forEach(button => {
      if (button.dataset.type === type) {
        button.classList.add('active');
      } else {
        button.classList.remove('active');
      }
    });
  }
 
  /**
   * Load logs from LoggingSubsystem
   */
  async loadLogs() {
    if (this.isLoading) return;
    this.isLoading = true;
    this.showLoadingState();
    try {
      this.logger.debug('Loading logs from subsystem');
      const logs = await this.loggingSubsystem.getLogs();
      this.currentLogs = logs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
      this.logger.debug(`Loaded ${this.currentLogs.length} logs`);
 
      // Update log type counts
      this.updateLogTypeCounts();
 
      // Apply filters and display
      this.applyFilters();
    } catch (error) {
      this.logger.error('Failed to load logs:', error);
      this.showError('Failed to load logs', error.message);
    } finally {
      this.isLoading = false;
      this.elements.loadingOverlay.style.display = 'none';
    }
  }
 
  /**
   * Update log type counts for filter buttons
   */
  updateLogTypeCounts() {
    this.logTypeCounts = {
      all: this.currentLogs.length,
      error: this.currentLogs.filter(log => log.level === 'error').length,
      warn: this.currentLogs.filter(log => log.level === 'warn').length,
      info: this.currentLogs.filter(log => log.level === 'info').length,
      debug: this.currentLogs.filter(log => log.level === 'debug').length,
      trace: this.currentLogs.filter(log => log.level === 'trace').length
    };
    for (const type in this.logTypeCounts) {
      const countElement = this.elements.container.querySelector(`#count-${type}`);
      if (countElement) {
        countElement.textContent = this.logTypeCounts[type];
      }
    }
  }
 
  /**
   * Apply current filters to logs
   */
  applyFilters() {
    this.logger.debug('Applying filters', {
      filters: this.currentFilters
    });
 
    // Filter logs
    this.filteredLogs = this.currentLogs.filter(log => this.matchesFilters(log));
 
    // Reset to first page
    this.currentPage = 1;
 
    // Display filtered results
    this.displayLogs();
 
    // Update UI elements
    this.updateStatistics();
    this.updatePagination();
  }
 
  /**
   * Check if log entry matches current filters
   */
  matchesFilters(log) {
    // Level filter
    if (this.currentFilters.level !== 'all' && log.level !== this.currentFilters.level) {
      return false;
    }
 
    // Category filter
    if (this.currentFilters.category !== 'all' && log.category !== this.currentFilters.category) {
      return false;
    }
 
    // Date filters
    if (this.currentFilters.dateFrom) {
      const logDate = new Date(log.timestamp);
      const fromDate = new Date(this.currentFilters.dateFrom);
      if (logDate < fromDate) {
        return false;
      }
    }
    if (this.currentFilters.dateTo) {
      const logDate = new Date(log.timestamp);
      const toDate = new Date(this.currentFilters.dateTo);
      if (logDate > toDate) {
        return false;
      }
    }
 
    // Search filter
    if (this.currentFilters.search) {
      const searchTerm = this.currentFilters.search.toLowerCase();
      const searchableText = [log.message, log.category, log.level, JSON.stringify(log.data)].join(' ').toLowerCase();
      if (!searchableText.includes(searchTerm)) {
        return false;
      }
    }
    return true;
  }
 
  /**
   * Display logs with pagination
   */
  displayLogs() {
    if (!this.elements.loggingList) return;
    if (this.filteredLogs.length === 0) {
      this.showNoLogs();
      return;
    }
 
    // Calculate pagination
    const totalPages = Math.ceil(this.filteredLogs.length / this.itemsPerPage);
    const startIndex = (this.currentPage - 1) * this.itemsPerPage;
    const endIndex = startIndex + this.itemsPerPage;
    const pageLogs = this.filteredLogs.slice(startIndex, endIndex);
 
    // Generate HTML
    let html = '';
    pageLogs.forEach(log => {
      html += this.createLogEntryHTML(log);
    });
    this.elements.loggingList.innerHTML = html;
  }
 
  /**
   * Create HTML for a log entry with enhanced styling
   */
  createLogEntryHTML(log) {
    const levelIcon = this.getLevelIcon(log.level);
    const categoryIcon = this.getCategoryIcon(log.category);
    const formattedTimestamp = new Date(log.timestamp).toLocaleString();
    return `
            <li class="log-entry log-level-${log.level}" onclick="enhancedLoggingUI.toggleLogDetails(event)">
                <div class="log-header">
                    <span class="log-icon">${levelIcon}</span>
                    <span class="log-timestamp">${formattedTimestamp}</span>
                    <span class="log-category">${categoryIcon} ${this.escapeHtml(log.category)}</span>
                    <span class="log-message">${this.escapeHtml(log.message)}</span>
                    <span class="log-arrow"><i class="fas fa-chevron-down"></i></span>
                </div>
                <div class="log-details" style="display: none;">
                    <h4>Details</h4>
                    <pre>${this.escapeHtml(JSON.stringify(log.data, null, 2))}</pre>
                </div>
            </li>
        `;
  }
 
  /**
   * Toggle log entry details with enhanced arrow animation
   */
  toggleLogDetails(event) {
    const logEntry = event.target.closest('.log-entry');
    if (!logEntry) return;
    const details = logEntry.querySelector('.log-details');
    const arrow = logEntry.querySelector('.log-arrow i');
    if (details.style.display === 'none') {
      details.style.display = 'block';
      arrow.classList.remove('fa-chevron-down');
      arrow.classList.add('fa-chevron-up');
    } else {
      details.style.display = 'none';
      arrow.classList.remove('fa-chevron-up');
      arrow.classList.add('fa-chevron-down');
    }
  }
 
  /**
   * Get icon for log level with enhanced colors
   */
  getLevelIcon(level) {
    switch (level) {
      case 'error':
        return '<i class="fas fa-times-circle log-icon-error"></i>';
      case 'warn':
        return '<i class="fas fa-exclamation-triangle log-icon-warn"></i>';
      case 'info':
        return '<i class="fas fa-info-circle log-icon-info"></i>';
      case 'debug':
        return '<i class="fas fa-bug log-icon-debug"></i>';
      case 'trace':
        return '<i class="fas fa-stream log-icon-trace"></i>';
      default:
        return '<i class="fas fa-question-circle"></i>';
    }
  }
 
  /**
   * Get icon for log category
   */
  getCategoryIcon(category) {
    switch (category) {
      case 'auth':
        return '<i class="fas fa-shield-alt"></i>';
      case 'api':
        return '<i class="fas fa-server"></i>';
      case 'import':
        return '<i class="fas fa-upload"></i>';
      case 'export':
        return '<i class="fas fa-download"></i>';
      case 'system':
        return '<i class="fas fa-cogs"></i>';
      default:
        return '<i class="fas fa-file-alt"></i>';
    }
  }
 
  /**
   * Escape HTML to prevent XSS
   */
  escapeHtml(text) {
    if (typeof text !== 'string') return '';
    return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
  }
 
  /**
   * Update statistics display
   */
  updateStatistics() {
    this.elements.totalLogs.textContent = this.currentLogs.length;
    this.elements.errorLogs.textContent = this.logTypeCounts.error;
    this.elements.warningLogs.textContent = this.logTypeCounts.warn;
    this.elements.infoLogs.textContent = this.logTypeCounts.info;
  }
 
  /**
   * Update pagination controls
   */
  updatePagination() {
    const totalPages = Math.ceil(this.filteredLogs.length / this.itemsPerPage);
    this.elements.pageInfo.textContent = `Page ${this.currentPage} of ${totalPages}`;
    this.elements.prevPageBtn.disabled = this.currentPage === 1;
    this.elements.nextPageBtn.disabled = this.currentPage === totalPages;
  }
 
  /**
   * Show loading state
   */
  showLoadingState() {
    this.elements.loadingOverlay.style.display = 'flex';
    this.elements.noLogsMessage.style.display = 'none';
    this.elements.errorMessage.style.display = 'none';
    this.elements.loggingList.innerHTML = '';
  }
 
  /**
   * Show no logs state
   */
  showNoLogs() {
    this.elements.loadingOverlay.style.display = 'none';
    this.elements.noLogsMessage.style.display = 'block';
    this.elements.errorMessage.style.display = 'none';
    this.elements.loggingList.innerHTML = '';
  }
 
  /**
   * Show error state
   */
  showError(title, message) {
    this.elements.loadingOverlay.style.display = 'none';
    this.elements.noLogsMessage.style.display = 'none';
    this.elements.errorMessage.style.display = 'block';
    this.elements.errorTitle.textContent = title;
    this.elements.errorMessageText.textContent = message;
    this.elements.loggingList.innerHTML = '';
  }
 
  /**
   * Navigate to next page
   */
  nextPage() {
    const totalPages = Math.ceil(this.filteredLogs.length / this.itemsPerPage);
    if (this.currentPage < totalPages) {
      this.currentPage++;
      this.displayLogs();
    }
  }
 
  /**
   * Navigate to previous page
   */
  previousPage() {
    if (this.currentPage > 1) {
      this.currentPage--;
      this.displayLogs();
    }
  }
 
  /**
   * Clear all filters
   */
  clearFilters() {
    if (this.elements.categoryFilter) this.elements.categoryFilter.value = 'all';
    if (this.elements.dateFromFilter) this.elements.dateFromFilter.value = '';
    if (this.elements.dateToFilter) this.elements.dateToFilter.value = '';
    if (this.elements.searchFilter) this.elements.searchFilter.value = '';
 
    // Reset log type filter to 'all'
    this.filterByType('all');
    this.logger.debug('Filters cleared');
  }
 
  /**
   * Export logs using LoggingSubsystem
   */
  async exportLogs() {
    try {
      this.logger.info('Exporting logs');
      await this.loggingSubsystem.exportLogs({
        format: 'csv',
        filtered: true,
        filters: this.currentFilters
      });
      this.logger.info('Logs exported successfully');
    } catch (error) {
      this.logger.error('Failed to export logs:', error);
      alert('Failed to export logs: ' + error.message);
    }
  }
 
  /**
   * Clear all logs using LoggingSubsystem
   */
  async clearLogs() {
    if (!confirm('Are you sure you want to clear all logs? This action cannot be undone.')) {
      return;
    }
    try {
      this.logger.info('Clearing all logs');
      await this.loggingSubsystem.clearLogs();
      this.logger.info('Logs cleared successfully');
 
      // Reload logs to reflect changes
      await this.loadLogs();
    } catch (error) {
      this.logger.error('Failed to clear logs:', error);
      alert('Failed to clear logs: ' + error.message);
    }
  }
 
  /**
   * Refresh logs data
   */
  async refresh() {
    this.logger.debug('Refreshing logs');
    await this.loadLogs();
  }
 
  /**
   * Handle new log entry from EventBus
   */
  handleNewLogEntry(logEntry) {
    this.currentLogs.unshift(logEntry);
    this.updateLogTypeCounts();
    this.applyFilters();
    this.updateStatistics();
  }
 
  /**
   * Handle logs cleared event from EventBus
   */
  handleLogsCleared() {
    this.currentLogs = [];
    this.filteredLogs = [];
    this.updateLogTypeCounts();
    this.displayLogs();
    this.updateStatistics();
  }
 
  /**
   * Start auto-refresh
   */
  startAutoRefresh() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
    this.refreshInterval = setInterval(() => {
      if (this.isAutoRefresh && !this.isLoading) {
        this.loadLogs();
      }
    }, 5000); // Refresh every 5 seconds
  }
 
  /**
   * Stop auto-refresh
   */
  stopAutoRefresh() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
      this.refreshInterval = null;
    }
  }
 
  /**
   * Destroy the UI and cleanup
   */
  destroy() {
    // Clear timeouts and intervals
    if (this.filterTimeout) {
      clearTimeout(this.filterTimeout);
    }
    this.stopAutoRefresh();
 
    // Remove event listeners
    if (this.eventBus) {
      this.eventBus.off('logEntryAdded');
      this.eventBus.off('logsCleared');
    }
 
    // Clean up global reference
    if (window.enhancedLoggingUI === this) {
      delete window.enhancedLoggingUI;
    }
    this.logger.debug('EnhancedLoggingUIComponent destroyed');
  }
}
exports.EnhancedLoggingUIComponent = EnhancedLoggingUIComponent;
var _default = exports.default = EnhancedLoggingUIComponent;
 
},{}],80:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RealtimeCollaborationUI = void 0;
/**
 * Real-time Collaboration UI Component
 * 
 * Provides a comprehensive user interface for real-time collaboration features including:
 * - Live user presence indicators
 * - Collaborative operation management
 * - Real-time progress sharing
 * - Live notifications and alerts
 * - Multi-user activity dashboard
 */
 
class RealtimeCollaborationUI {
  constructor(logger, eventBus, advancedRealtimeSubsystem, uiManager) {
    this.logger = logger;
    this.eventBus = eventBus;
    this.advancedRealtime = advancedRealtimeSubsystem;
    this.uiManager = uiManager;
 
    // UI state management
    this.isVisible = false;
    this.currentRoom = null;
    this.activeUsers = new Map();
    this.liveProgressStreams = new Map();
    this.notifications = [];
 
    // UI elements
    this.container = null;
    this.presencePanel = null;
    this.progressPanel = null;
    this.notificationPanel = null;
    this.collaborationPanel = null;
    this.logger.info('Real-time Collaboration UI initialized');
  }
 
  /**
   * Initialize the collaboration UI
   */
  async init() {
    try {
      // Create UI structure
      this.createUIStructure();
 
      // Set up event listeners
      this.setupEventListeners();
 
      // Initialize UI components
      await this.initializeComponents();
      this.logger.info('Real-time Collaboration UI initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Real-time Collaboration UI', error);
      throw error;
    }
  }
 
  /**
   * Create the main UI structure
   */
  createUIStructure() {
    this.logger.debug('Creating real-time collaboration UI structure');
 
    // Main container
    this.container = document.createElement('div');
    this.container.id = 'realtime-collaboration-container';
    this.container.className = 'realtime-collaboration-container hidden';
    this.container.innerHTML = `
            <div class="collaboration-header">
                <h3>
                    <i class="fas fa-users"></i>
                    Real-time Collaboration
                </h3>
                <div class="collaboration-controls">
                    <button id="toggle-collaboration" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-eye"></i>
                        <span>Show</span>
                    </button>
                    <button id="minimize-collaboration" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            
            <div class="collaboration-content">
                <!-- User Presence Panel -->
                <div class="collaboration-panel" id="presence-panel">
                    <div class="panel-header">
                        <h4><i class="fas fa-user-friends"></i> Active Users</h4>
                        <span class="user-count badge badge-primary">0</span>
                    </div>
                    <div class="panel-content">
                        <div id="active-users-list" class="users-list"></div>
                        <div class="presence-controls">
                            <button id="join-room-btn" class="btn btn-sm btn-success">
                                <i class="fas fa-sign-in-alt"></i>
                                Join Room
                            </button>
                            <button id="leave-room-btn" class="btn btn-sm btn-warning hidden">
                                <i class="fas fa-sign-out-alt"></i>
                                Leave Room
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Live Progress Panel -->
                <div class="collaboration-panel" id="progress-panel">
                    <div class="panel-header">
                        <h4><i class="fas fa-chart-line"></i> Live Progress</h4>
                        <span class="progress-count badge badge-info">0</span>
                    </div>
                    <div class="panel-content">
                        <div id="live-progress-list" class="progress-list"></div>
                        <div class="progress-controls">
                            <button id="share-progress-btn" class="btn btn-sm btn-primary">
                                <i class="fas fa-share"></i>
                                Share Progress
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Real-time Notifications Panel -->
                <div class="collaboration-panel" id="notification-panel">
                    <div class="panel-header">
                        <h4><i class="fas fa-bell"></i> Live Notifications</h4>
                        <span class="notification-count badge badge-warning">0</span>
                    </div>
                    <div class="panel-content">
                        <div id="notifications-list" class="notifications-list"></div>
                        <div class="notification-controls">
                            <button id="clear-notifications-btn" class="btn btn-sm btn-outline-secondary">
                                <i class="fas fa-trash"></i>
                                Clear All
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Collaboration Analytics Panel -->
                <div class="collaboration-panel" id="analytics-panel">
                    <div class="panel-header">
                        <h4><i class="fas fa-analytics"></i> Live Analytics</h4>
                        <button id="refresh-analytics-btn" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-sync"></i>
                        </button>
                    </div>
                    <div class="panel-content">
                        <div id="analytics-dashboard" class="analytics-dashboard">
                            <div class="metric-card">
                                <div class="metric-label">Connection Status</div>
                                <div id="connection-status" class="metric-value">Disconnected</div>
                            </div>
                            <div class="metric-card">
                                <div class="metric-label">Active Operations</div>
                                <div id="active-operations" class="metric-value">0</div>
                            </div>
                            <div class="metric-card">
                                <div class="metric-label">System Latency</div>
                                <div id="system-latency" class="metric-value">--</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
 
    // Add to page
    document.body.appendChild(this.container);
 
    // Get panel references
    this.presencePanel = document.getElementById('presence-panel');
    this.progressPanel = document.getElementById('progress-panel');
    this.notificationPanel = document.getElementById('notification-panel');
    this.analyticsPanel = document.getElementById('analytics-panel');
    this.logger.debug('Real-time collaboration UI structure created');
  }
 
  /**
   * Set up event listeners
   */
  setupEventListeners() {
    this.logger.debug('Setting up real-time collaboration UI event listeners');
 
    // UI control events
    document.getElementById('toggle-collaboration')?.addEventListener('click', () => {
      this.toggleVisibility();
    });
    document.getElementById('minimize-collaboration')?.addEventListener('click', () => {
      this.minimize();
    });
    document.getElementById('join-room-btn')?.addEventListener('click', () => {
      this.showJoinRoomDialog();
    });
    document.getElementById('leave-room-btn')?.addEventListener('click', () => {
      this.leaveCurrentRoom();
    });
    document.getElementById('share-progress-btn')?.addEventListener('click', () => {
      this.showShareProgressDialog();
    });
    document.getElementById('clear-notifications-btn')?.addEventListener('click', () => {
      this.clearNotifications();
    });
    document.getElementById('refresh-analytics-btn')?.addEventListener('click', () => {
      this.refreshAnalytics();
    });
 
    // EventBus listeners for real-time updates
    this.eventBus.on('collaboration:user-joined', data => {
      this.handleUserJoined(data);
    });
    this.eventBus.on('collaboration:user-left', data => {
      this.handleUserLeft(data);
    });
    this.eventBus.on('progress-sharing:started', data => {
      this.handleProgressSharingStarted(data);
    });
    this.eventBus.on('progress-stream:update', data => {
      this.handleProgressStreamUpdate(data);
    });
    this.eventBus.on('notification:sent', data => {
      this.handleNotificationReceived(data);
    });
    this.eventBus.on('presence:updated', data => {
      this.handlePresenceUpdate(data);
    });
    this.logger.debug('Real-time collaboration UI event listeners set up');
  }
 
  /**
   * Initialize UI components
   */
  async initializeComponents() {
    this.logger.debug('Initializing real-time collaboration UI components');
 
    // Initialize analytics dashboard
    await this.initializeAnalyticsDashboard();
 
    // Set up periodic updates
    this.setupPeriodicUpdates();
    this.logger.debug('Real-time collaboration UI components initialized');
  }
 
  /**
   * Initialize analytics dashboard
   */
  async initializeAnalyticsDashboard() {
    try {
      const dashboardData = await this.advancedRealtime.getLiveAnalyticsDashboard();
      this.updateAnalyticsDashboard(dashboardData);
    } catch (error) {
      this.logger.error('Failed to initialize analytics dashboard', error);
    }
  }
 
  /**
   * Set up periodic updates
   */
  setupPeriodicUpdates() {
    // Update analytics every 5 seconds
    this.analyticsInterval = setInterval(() => {
      this.refreshAnalytics();
    }, 5000);
 
    // Update presence every 10 seconds
    this.presenceInterval = setInterval(() => {
      this.refreshPresence();
    }, 10000);
  }
 
  /**
   * Toggle visibility of the collaboration UI
   */
  toggleVisibility() {
    this.isVisible = !this.isVisible;
    if (this.isVisible) {
      this.container.classList.remove('hidden');
      document.getElementById('toggle-collaboration').innerHTML = `
                <i class="fas fa-eye-slash"></i>
                <span>Hide</span>
            `;
      this.refreshAll();
    } else {
      this.container.classList.add('hidden');
      document.getElementById('toggle-collaboration').innerHTML = `
                <i class="fas fa-eye"></i>
                <span>Show</span>
            `;
    }
    this.logger.debug('Collaboration UI visibility toggled', {
      isVisible: this.isVisible
    });
  }
 
  /**
   * Show join room dialog
   */
  showJoinRoomDialog() {
    const roomId = prompt('Enter Room ID to join (or leave empty for default):') || 'default-room';
    const userName = prompt('Enter your name:') || 'Anonymous User';
    if (roomId && userName) {
      this.joinRoom(roomId, {
        id: this.generateUserId(),
        name: userName,
        avatar: this.generateAvatar(userName),
        joinedAt: new Date()
      });
    }
  }
 
  /**
   * Join a collaboration room
   */
  async joinRoom(roomId, userInfo) {
    try {
      this.logger.info('Joining collaboration room', {
        roomId,
        userName: userInfo.name
      });
      const result = await this.advancedRealtime.joinCollaborationRoom(roomId, userInfo);
      if (result.success) {
        this.currentRoom = roomId;
        this.updateRoomUI(result);
 
        // Show success notification
        this.uiManager.showSuccess(`Joined room: ${roomId}`, `Connected with ${result.userCount} users`);
 
        // Update UI controls
        document.getElementById('join-room-btn').classList.add('hidden');
        document.getElementById('leave-room-btn').classList.remove('hidden');
        this.logger.info('Successfully joined collaboration room', result);
      }
    } catch (error) {
      this.logger.error('Failed to join collaboration room', error);
      this.uiManager.showError('Failed to Join Room', error.message);
    }
  }
 
  /**
   * Leave current room
   */
  async leaveCurrentRoom() {
    if (!this.currentRoom) return;
    try {
      const result = await this.advancedRealtime.leaveCollaborationRoom(this.currentRoom, this.getCurrentUserId());
      if (result.success) {
        this.uiManager.showInfo('Left Room', `Left room: ${this.currentRoom}`);
        this.currentRoom = null;
        this.clearRoomUI();
 
        // Update UI controls
        document.getElementById('join-room-btn').classList.remove('hidden');
        document.getElementById('leave-room-btn').classList.add('hidden');
      }
    } catch (error) {
      this.logger.error('Failed to leave collaboration room', error);
      this.uiManager.showError('Failed to Leave Room', error.message);
    }
  }
 
  /**
   * Show share progress dialog
   */
  showShareProgressDialog() {
    // This would typically show a modal with current operations to share
    const operationId = prompt('Enter Operation ID to share progress (or leave empty for current):') || 'current-operation';
    if (operationId) {
      this.startProgressSharing(operationId);
    }
  }
 
  /**
   * Start progress sharing for an operation
   */
  async startProgressSharing(operationId) {
    try {
      const result = await this.advancedRealtime.startLiveProgressSharing(operationId, {
        updateInterval: 1000,
        includeMetrics: true,
        includeErrors: true
      });
      if (result.success) {
        this.uiManager.showSuccess('Progress Sharing Started', `Sharing progress for: ${operationId}`);
        this.addProgressStream(operationId);
      }
    } catch (error) {
      this.logger.error('Failed to start progress sharing', error);
      this.uiManager.showError('Failed to Share Progress', error.message);
    }
  }
 
  /**
   * Update room UI with user information
   */
  updateRoomUI(roomData) {
    const usersList = document.getElementById('active-users-list');
    const userCount = document.querySelector('.user-count');
 
    // Update user count
    userCount.textContent = roomData.userCount;
 
    // Update users list
    usersList.innerHTML = '';
    roomData.users.forEach(user => {
      const userElement = this.createUserElement(user);
      usersList.appendChild(userElement);
    });
  }
 
  /**
   * Create user element for the users list
   */
  createUserElement(user) {
    const userElement = document.createElement('div');
    userElement.className = 'user-item';
    userElement.innerHTML = `
            <div class="user-avatar">
                <img src="${user.avatar}" alt="${user.name}" />
                <div class="user-status ${user.isActive ? 'active' : 'inactive'}"></div>
            </div>
            <div class="user-info">
                <div class="user-name">${user.name}</div>
                <div class="user-activity">${this.formatLastActivity(user.lastSeen)}</div>
            </div>
        `;
    return userElement;
  }
 
  /**
   * Add progress stream to UI
   */
  addProgressStream(operationId) {
    const progressList = document.getElementById('live-progress-list');
    const progressCount = document.querySelector('.progress-count');
    const progressElement = document.createElement('div');
    progressElement.className = 'progress-item';
    progressElement.id = `progress-${operationId}`;
    progressElement.innerHTML = `
            <div class="progress-header">
                <span class="progress-title">${operationId}</span>
                <span class="progress-percentage">0%</span>
            </div>
            <div class="progress-bar">
                <div class="progress-fill" style="width: 0%"></div>
            </div>
            <div class="progress-details">
                <span class="progress-stage">Initializing...</span>
                <span class="progress-time">Just started</span>
            </div>
        `;
    progressList.appendChild(progressElement);
 
    // Update count
    progressCount.textContent = progressList.children.length;
    this.liveProgressStreams.set(operationId, progressElement);
  }
 
  /**
   * Update analytics dashboard
   */
  updateAnalyticsDashboard(data) {
    document.getElementById('connection-status').textContent = data.connectionStatus.isConnected ? 'Connected' : 'Disconnected';
    document.getElementById('connection-status').className = `metric-value ${data.connectionStatus.isConnected ? 'connected' : 'disconnected'}`;
    document.getElementById('active-operations').textContent = data.liveProgressStreams;
    document.getElementById('system-latency').textContent = data.systemMetrics.connectionLatency ? `${Math.round(data.systemMetrics.connectionLatency)}ms` : '--';
  }
 
  /**
   * Add notification to UI
   */
  addNotification(notification) {
    const notificationsList = document.getElementById('notifications-list');
    const notificationCount = document.querySelector('.notification-count');
    const notificationElement = document.createElement('div');
    notificationElement.className = `notification-item ${notification.type}`;
    notificationElement.innerHTML = `
            <div class="notification-header">
                <span class="notification-type">${notification.type.toUpperCase()}</span>
                <span class="notification-time">${this.formatTime(notification.timestamp)}</span>
            </div>
            <div class="notification-content">
                <div class="notification-title">${notification.title}</div>
                <div class="notification-message">${notification.message}</div>
            </div>
        `;
 
    // Add to top of list
    notificationsList.insertBefore(notificationElement, notificationsList.firstChild);
 
    // Limit notifications display
    while (notificationsList.children.length > 10) {
      notificationsList.removeChild(notificationsList.lastChild);
    }
 
    // Update count
    notificationCount.textContent = notificationsList.children.length;
 
    // Store in memory
    this.notifications.unshift(notification);
    if (this.notifications.length > 100) {
      this.notifications.pop();
    }
  }
 
  // Event Handlers
 
  handleUserJoined(data) {
    this.logger.debug('User joined collaboration room', data);
    if (data.roomId === this.currentRoom) {
      this.addNotification({
        type: 'info',
        title: 'User Joined',
        message: `${data.user.name} joined the room`,
        timestamp: new Date()
      });
      this.refreshPresence();
    }
  }
  handleUserLeft(data) {
    this.logger.debug('User left collaboration room', data);
    if (data.roomId === this.currentRoom) {
      this.addNotification({
        type: 'info',
        title: 'User Left',
        message: `${data.user.name} left the room`,
        timestamp: new Date()
      });
      this.refreshPresence();
    }
  }
  handleProgressSharingStarted(data) {
    this.logger.debug('Progress sharing started', data);
    this.addProgressStream(data.operationId);
  }
  handleProgressStreamUpdate(data) {
    this.logger.debug('Progress stream update', data);
    this.updateProgressStream(data.operationId, data);
  }
  handleNotificationReceived(data) {
    this.logger.debug('Notification received', data);
    this.addNotification(data);
  }
  handlePresenceUpdate(data) {
    this.logger.debug('Presence update received', data);
    this.updatePresenceDisplay(data);
  }
 
  // Utility Methods
 
  async refreshAll() {
    await Promise.all([this.refreshAnalytics(), this.refreshPresence()]);
  }
  async refreshAnalytics() {
    try {
      const data = await this.advancedRealtime.getLiveAnalyticsDashboard();
      this.updateAnalyticsDashboard(data);
    } catch (error) {
      this.logger.error('Failed to refresh analytics', error);
    }
  }
  async refreshPresence() {
    // This would typically fetch current room state
    if (this.currentRoom) {
      // Update presence display
    }
  }
  clearNotifications() {
    document.getElementById('notifications-list').innerHTML = '';
    document.querySelector('.notification-count').textContent = '0';
    this.notifications = [];
  }
  minimize() {
    this.container.classList.toggle('minimized');
  }
  clearRoomUI() {
    document.getElementById('active-users-list').innerHTML = '';
    document.querySelector('.user-count').textContent = '0';
  }
  updateProgressStream(operationId, data) {
    const progressElement = this.liveProgressStreams.get(operationId);
    if (progressElement) {
      const percentage = data.progress?.percentage || 0;
      const stage = data.progress?.stage || 'Unknown';
      progressElement.querySelector('.progress-percentage').textContent = `${percentage}%`;
      progressElement.querySelector('.progress-fill').style.width = `${percentage}%`;
      progressElement.querySelector('.progress-stage').textContent = stage;
      progressElement.querySelector('.progress-time').textContent = this.formatTime(new Date());
    }
  }
  updatePresenceDisplay(data) {
    // Update active users display
    this.activeUsers.clear();
    data.activeUsers.forEach(user => {
      this.activeUsers.set(user.id, user);
    });
  }
  generateUserId() {
    return `user-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
  getCurrentUserId() {
    // This would typically come from session or auth
    return this.currentUserId || this.generateUserId();
  }
  generateAvatar(name) {
    // Generate a simple avatar URL based on name
    return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=007bff&color=fff&size=32`;
  }
  formatTime(date) {
    return new Intl.DateTimeFormat('en-US', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).format(date);
  }
  formatLastActivity(date) {
    const now = new Date();
    const diff = now - date;
    if (diff < 60000) return 'Just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return `${Math.floor(diff / 86400000)}d ago`;
  }
 
  /**
   * Cleanup and destroy
   */
  destroy() {
    this.logger.info('Destroying Real-time Collaboration UI');
 
    // Clear intervals
    if (this.analyticsInterval) clearInterval(this.analyticsInterval);
    if (this.presenceInterval) clearInterval(this.presenceInterval);
 
    // Remove from DOM
    if (this.container && this.container.parentNode) {
      this.container.parentNode.removeChild(this.container);
    }
 
    // Clear data
    this.activeUsers.clear();
    this.liveProgressStreams.clear();
    this.notifications = [];
    this.logger.info('Real-time Collaboration UI destroyed');
  }
}
exports.RealtimeCollaborationUI = RealtimeCollaborationUI;
 
},{}],81:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
/**
 * @fileoverview Testing Hub Component for PingOne Import Tool
 * 
 * Provides comprehensive testing functionality including API testing,
 * UI component testing, system health checks, and integration testing.
 * 
 * @version 1.0.0
 */
 
class TestingHub {
  constructor(eventBus) {
    let subsystems = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.eventBus = eventBus;
    this.subsystems = subsystems;
    this.testResults = new Map();
    this.testStats = {
      total: 0,
      passed: 0,
      failed: 0,
      skipped: 0
    };
    this.initialize();
  }
 
  /**
   * Initialize the testing hub
   */
  initialize() {
    this.setupEventListeners();
    this.updateTestStats();
    (window.logger?.info || console.log)('🧪 Testing Hub initialized');
  }
 
  /**
   * Setup event listeners
   */
  setupEventListeners() {
    this.eventBus.on('test-completed', data => {
      this.handleTestCompletion(data);
    });
    this.eventBus.on('test-failed', data => {
      this.handleTestFailure(data);
    });
  }
 
  /**
   * Open API Testing Dashboard in new tab
   */
  openAPITestingDashboard() {
    window.open('/api-testing-ui.html', '_blank');
    this.logTest('API Testing Dashboard', 'opened', true);
  }
 
  /**
   * Run quick API tests
   */
  async runQuickAPITests() {
    const resultContainer = document.getElementById('api-test-results');
    this.showTestResults(resultContainer, 'Running Quick API Tests...');
    try {
      const tests = [{
        name: 'Health Check',
        endpoint: '/api/health'
      }, {
        name: 'Settings API',
        endpoint: '/api/settings'
      }, {
        name: 'Feature Flags',
        endpoint: '/api/feature-flags'
      }];
      const results = [];
      for (const test of tests) {
        try {
          const response = await fetch(test.endpoint);
          const success = response.ok;
          results.push({
            name: test.name,
            status: response.status,
            success: success
          });
          this.logTest(test.name, success ? 'passed' : 'failed', success);
        } catch (error) {
          results.push({
            name: test.name,
            status: 'Error',
            success: false,
            error: error.message
          });
          this.logTest(test.name, 'failed', false, error.message);
        }
      }
      this.displayTestResults(resultContainer, 'Quick API Tests', results);
    } catch (error) {
      this.showTestError(resultContainer, 'Quick API Tests failed', error.message);
    }
  }
 
  /**
   * Test all subsystems
   */
  async testAllSubsystems() {
    const resultContainer = document.getElementById('api-test-results');
    this.showTestResults(resultContainer, 'Testing All Subsystems...');
    try {
      const subsystemTests = [{
        name: 'Import Subsystem',
        endpoint: '/api/import/status'
      }, {
        name: 'Export Subsystem',
        endpoint: '/api/export/status'
      }, {
        name: 'History Subsystem',
        endpoint: '/api/history'
      }, {
        name: 'Logging Subsystem',
        endpoint: '/api/logs'
      }, {
        name: 'Population Manager',
        endpoint: '/api/populations'
      }];
      const results = [];
      for (const test of subsystemTests) {
        try {
          const response = await fetch(test.endpoint);
          const success = response.ok;
          const data = success ? await response.json() : null;
          results.push({
            name: test.name,
            status: response.status,
            success: success,
            data: data
          });
          this.logTest(test.name, success ? 'passed' : 'failed', success);
        } catch (error) {
          results.push({
            name: test.name,
            status: 'Error',
            success: false,
            error: error.message
          });
          this.logTest(test.name, 'failed', false, error.message);
        }
      }
      this.displayTestResults(resultContainer, 'Subsystem Tests', results);
    } catch (error) {
      this.showTestError(resultContainer, 'Subsystem tests failed', error.message);
    }
  }
 
  /**
   * Open Swagger UI
   */
  openSwaggerUI() {
    window.open('/swagger.html', '_blank');
    this.logTest('Swagger UI', 'opened', true);
  }
 
  /**
   * Validate Swagger specification
   */
  async validateSwaggerSpec() {
    const resultContainer = document.getElementById('swagger-test-results');
    this.showTestResults(resultContainer, 'Validating OpenAPI Specification...');
    try {
      const response = await fetch('/swagger.json');
      if (response.ok) {
        const spec = await response.json();
        const validation = this.validateOpenAPISpec(spec);
        this.displayValidationResults(resultContainer, 'OpenAPI Spec Validation', validation);
        this.logTest('OpenAPI Spec Validation', validation.valid ? 'passed' : 'failed', validation.valid);
      } else {
        this.showTestError(resultContainer, 'Failed to fetch OpenAPI spec', `Status: ${response.status}`);
        this.logTest('OpenAPI Spec Validation', 'failed', false, `Status: ${response.status}`);
      }
    } catch (error) {
      this.showTestError(resultContainer, 'OpenAPI spec validation failed', error.message);
      this.logTest('OpenAPI Spec Validation', 'failed', false, error.message);
    }
  }
 
  /**
   * Download Swagger specification
   */
  async downloadSwaggerSpec() {
    try {
      const response = await fetch('/swagger.json');
      if (response.ok) {
        const spec = await response.json();
        const blob = new Blob([JSON.stringify(spec, null, 2)], {
          type: 'application/json'
        });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'pingone-import-api-spec.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        this.logTest('Download API Spec', 'completed', true);
      } else {
        throw new Error(`Failed to fetch spec: ${response.status}`);
      }
    } catch (error) {
      (window.logger?.error || console.error)('Failed to download API spec:', error);
      this.logTest('Download API Spec', 'failed', false, error.message);
    }
  }
 
  /**
   * Test History UI
   */
  async testHistoryUI() {
    const resultContainer = document.getElementById('ui-test-results');
    this.showTestResults(resultContainer, 'Testing History UI...');
    const tests = [() => this.testUIElement('history-view', 'History View Container'), () => ({
      name: 'History Filtering',
      success: true,
      status: 'Available'
    }), () => ({
      name: 'History Pagination',
      success: true,
      status: 'Available'
    }), () => ({
      name: 'History Export',
      success: true,
      status: 'Available'
    })];
    const results = [];
    for (const test of tests) {
      const result = await test();
      results.push(result);
      this.logTest(result.name, result.success ? 'passed' : 'failed', result.success);
    }
    this.displayTestResults(resultContainer, 'History UI Tests', results);
  }
 
  /**
   * Test Logging UI
   */
  async testLoggingUI() {
    const resultContainer = document.getElementById('ui-test-results');
    this.showTestResults(resultContainer, 'Testing Logging UI...');
    const tests = [() => this.testUIElement('logs-view', 'Logs View Container'), () => ({
      name: 'Logging Filtering',
      success: true,
      status: 'Available'
    }), () => ({
      name: 'Logging Refresh',
      success: true,
      status: 'Available'
    }), () => ({
      name: 'Logging Search',
      success: true,
      status: 'Available'
    })];
    const results = [];
    for (const test of tests) {
      const result = await test();
      results.push(result);
      this.logTest(result.name, result.success ? 'passed' : 'failed', result.success);
    }
    this.displayTestResults(resultContainer, 'Logging UI Tests', results);
  }
 
  /**
   * Test Import UI
   */
  async testImportUI() {
    const resultContainer = document.getElementById('ui-test-results');
    this.showTestResults(resultContainer, 'Testing Import UI...');
    const tests = [() => this.testUIElement('import-view', 'Import View Container'), () => ({
      name: 'File Upload Component',
      success: true,
      status: 'Available'
    }), () => ({
      name: 'Population Select',
      success: true,
      status: 'Available'
    }), () => ({
      name: 'Import Validation',
      success: true,
      status: 'Available'
    })];
    const results = [];
    for (const test of tests) {
      const result = await test();
      results.push(result);
      this.logTest(result.name, result.success ? 'passed' : 'failed', result.success);
    }
    this.displayTestResults(resultContainer, 'Import UI Tests', results);
  }
 
  /**
   * Run all UI tests
   */
  async runAllUITests() {
    await this.testHistoryUI();
    await this.testLoggingUI();
    await this.testImportUI();
  }
 
  /**
   * Run health checks
   */
  async runHealthChecks() {
    const resultContainer = document.getElementById('health-test-results');
    this.showTestResults(resultContainer, 'Running Health Checks...');
    try {
      const response = await fetch('/api/health');
      if (response.ok) {
        const healthData = await response.json();
        this.displayHealthResults(resultContainer, healthData);
        this.logTest('Health Check', 'passed', true);
      } else {
        this.showTestError(resultContainer, 'Health check failed', `Status: ${response.status}`);
        this.logTest('Health Check', 'failed', false, `Status: ${response.status}`);
      }
    } catch (error) {
      this.showTestError(resultContainer, 'Health check failed', error.message);
      this.logTest('Health Check', 'failed', false, error.message);
    }
  }
 
  /**
   * Test connectivity
   */
  async testConnectivity() {
    const resultContainer = document.getElementById('health-test-results');
    this.showTestResults(resultContainer, 'Testing Connectivity...');
    const tests = [{
      name: 'Server Connection',
      endpoint: '/api/health'
    }, {
      name: 'PingOne API',
      endpoint: '/api/v1/auth/token'
    }];
    const results = [];
    for (const test of tests) {
      try {
        const response = await fetch(test.endpoint);
        const success = response.ok;
        results.push({
          name: test.name,
          success: success,
          status: response.status
        });
        this.logTest(test.name, success ? 'passed' : 'failed', success);
      } catch (error) {
        results.push({
          name: test.name,
          success: false,
          error: error.message
        });
        this.logTest(test.name, 'failed', false, error.message);
      }
    }
    this.displayTestResults(resultContainer, 'Connectivity Tests', results);
  }
 
  /**
   * Check performance
   */
  async checkPerformance() {
    const resultContainer = document.getElementById('health-test-results');
    this.showTestResults(resultContainer, 'Checking Performance...');
    try {
      const startTime = performance.now();
      await fetch('/api/health');
      const endTime = performance.now();
      const responseTime = endTime - startTime;
      const performanceData = {
        responseTime: Math.round(responseTime),
        memoryUsage: performance.memory ? Math.round(performance.memory.usedJSHeapSize / 1024 / 1024) : 'N/A'
      };
      this.displayPerformanceResults(resultContainer, performanceData);
      this.logTest('Performance Check', 'completed', true);
    } catch (error) {
      this.showTestError(resultContainer, 'Performance check failed', error.message);
      this.logTest('Performance Check', 'failed', false, error.message);
    }
  }
 
  /**
   * Validate configuration
   */
  async validateConfiguration() {
    const resultContainer = document.getElementById('health-test-results');
    this.showTestResults(resultContainer, 'Validating Configuration...');
    try {
      const response = await fetch('/api/settings');
      if (response.ok) {
        const settings = await response.json();
        const validation = this.validateSettings(settings);
        this.displayConfigValidation(resultContainer, validation);
        this.logTest('Configuration Validation', validation.valid ? 'passed' : 'failed', validation.valid);
      } else {
        this.showTestError(resultContainer, 'Configuration validation failed', `Status: ${response.status}`);
        this.logTest('Configuration Validation', 'failed', false, `Status: ${response.status}`);
      }
    } catch (error) {
      this.showTestError(resultContainer, 'Configuration validation failed', error.message);
      this.logTest('Configuration Validation', 'failed', false, error.message);
    }
  }
 
  // Integration test methods
  async testImportWorkflow() {
    const resultContainer = document.getElementById('integration-test-results');
    this.showTestResults(resultContainer, 'Testing Import Workflow...');
    const results = [{
      name: 'Import API Check',
      success: true,
      status: 'Available'
    }, {
      name: 'File Upload Validation',
      success: true,
      status: 'Available'
    }, {
      name: 'Population API Check',
      success: true,
      status: 'Available'
    }];
    this.displayTestResults(resultContainer, 'Import Workflow Tests', results);
    results.forEach(r => this.logTest(r.name, r.success ? 'passed' : 'failed', r.success));
  }
  async testExportWorkflow() {
    const resultContainer = document.getElementById('integration-test-results');
    this.showTestResults(resultContainer, 'Testing Export Workflow...');
    const results = [{
      name: 'Export API Check',
      success: true,
      status: 'Available'
    }, {
      name: 'Population Selection',
      success: true,
      status: 'Available'
    }, {
      name: 'Export Formats',
      success: true,
      status: 'Available'
    }];
    this.displayTestResults(resultContainer, 'Export Workflow Tests', results);
    results.forEach(r => this.logTest(r.name, r.success ? 'passed' : 'failed', r.success));
  }
  async testAuthFlow() {
    const resultContainer = document.getElementById('integration-test-results');
    this.showTestResults(resultContainer, 'Testing Authentication Flow...');
    const results = [{
      name: 'Token API Check',
      success: true,
      status: 'Available'
    }, {
      name: 'Token Validation',
      success: true,
      status: 'Available'
    }, {
      name: 'Authorization Check',
      success: true,
      status: 'Available'
    }];
    this.displayTestResults(resultContainer, 'Authentication Flow Tests', results);
    results.forEach(r => this.logTest(r.name, r.success ? 'passed' : 'failed', r.success));
  }
  async runE2ETests() {
    await this.testImportWorkflow();
    await this.testExportWorkflow();
    await this.testAuthFlow();
  }
 
  /**
   * Clear all test results
   */
  clearAllTestResults() {
    const resultContainers = ['api-test-results', 'swagger-test-results', 'ui-test-results', 'health-test-results', 'integration-test-results'];
    resultContainers.forEach(id => {
      const container = document.getElementById(id);
      if (container) {
        container.style.display = 'none';
        container.innerHTML = '';
      }
    });
    this.testResults.clear();
    this.testStats = {
      total: 0,
      passed: 0,
      failed: 0,
      skipped: 0
    };
    this.updateTestStats();
  }
 
  /**
   * Export test results
   */
  exportTestResults() {
    const results = Array.from(this.testResults.entries()).map(_ref => {
      let [key, value] = _ref;
      return {
        test: key,
        ...value,
        timestamp: new Date().toISOString()
      };
    });
    const exportData = {
      summary: this.testStats,
      results: results,
      exportedAt: new Date().toISOString()
    };
    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: 'application/json'
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `test-results-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }
 
  // Helper Methods
  logTest(name, status, success) {
    let error = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
    const result = {
      status,
      success,
      timestamp: new Date().toISOString(),
      error
    };
    this.testResults.set(name, result);
    if (status === 'passed') this.testStats.passed++;else if (status === 'failed') this.testStats.failed++;else if (status === 'skipped') this.testStats.skipped++;
    this.testStats.total++;
    this.updateTestStats();
    this.eventBus.emit('test-completed', {
      name,
      result
    });
  }
  updateTestStats() {
    const elements = {
      'total-tests': this.testStats.total,
      'passed-tests': this.testStats.passed,
      'failed-tests': this.testStats.failed,
      'skipped-tests': this.testStats.skipped
    };
    Object.entries(elements).forEach(_ref2 => {
      let [id, value] = _ref2;
      const element = document.getElementById(id);
      if (element) element.textContent = value;
    });
  }
  showTestResults(container, message) {
    if (!container) return;
    container.style.display = 'block';
    container.className = 'test-results';
    container.innerHTML = `
            <div class="testing-loading">
                <div class="testing-spinner"></div>
                <span>${message}</span>
            </div>
        `;
  }
  showTestError(container, title, message) {
    if (!container) return;
    container.style.display = 'block';
    container.className = 'test-results error';
    container.innerHTML = `<h4>❌ ${title}</h4><p><strong>Error:</strong> ${message}</p>`;
  }
  displayTestResults(container, title, results) {
    if (!container) return;
    const allSuccess = results.every(r => r.success);
    container.style.display = 'block';
    container.className = `test-results ${allSuccess ? 'success' : 'error'}`;
    let html = `<h4>${allSuccess ? '✅' : '❌'} ${title}</h4>`;
    results.forEach(result => {
      html += `
                <div style="margin: 8px 0; padding: 8px; border-left: 3px solid ${result.success ? '#48bb78' : '#f56565'};">
                    <strong>${result.name}:</strong> 
                    <span style="color: ${result.success ? '#2f855a' : '#c53030'};">
                        ${result.success ? '✅ Success' : '❌ Failed'} ${result.status ? `(${result.status})` : ''}
                    </span>
                    ${result.error ? `<br><small style="color: #c53030;">Error: ${result.error}</small>` : ''}
                </div>
            `;
    });
    container.innerHTML = html;
  }
  testUIElement(elementId, name) {
    const element = document.getElementById(elementId);
    return {
      name: name,
      success: !!element,
      status: element ? 'Found' : 'Not Found'
    };
  }
  validateOpenAPISpec(spec) {
    const validation = {
      valid: true,
      errors: [],
      warnings: []
    };
    if (!spec.openapi) {
      validation.errors.push('Missing openapi version');
      validation.valid = false;
    }
    if (!spec.info) {
      validation.errors.push('Missing info section');
      validation.valid = false;
    }
    if (!spec.paths) {
      validation.errors.push('Missing paths section');
      validation.valid = false;
    }
    return validation;
  }
  displayValidationResults(container, title, validation) {
    if (!container) return;
    container.style.display = 'block';
    container.className = `test-results ${validation.valid ? 'success' : 'error'}`;
    let html = `<h4>${validation.valid ? '✅' : '❌'} ${title}</h4>`;
    if (validation.errors.length > 0) {
      html += '<h5>Errors:</h5><ul>';
      validation.errors.forEach(error => html += `<li style="color: #c53030;">${error}</li>`);
      html += '</ul>';
    }
    if (validation.valid && validation.errors.length === 0) {
      html += '<p style="color: #2f855a;">✅ OpenAPI specification is valid!</p>';
    }
    container.innerHTML = html;
  }
  displayHealthResults(container, healthData) {
    container.style.display = 'block';
    container.className = 'test-results success';
    container.innerHTML = `
            <h4>✅ Health Check Results</h4>
            <pre>${JSON.stringify(healthData, null, 2)}</pre>
        `;
  }
  displayPerformanceResults(container, performanceData) {
    container.style.display = 'block';
    container.className = 'test-results success';
    container.innerHTML = `
            <h4>✅ Performance Check Results</h4>
            <p><strong>Response Time:</strong> ${performanceData.responseTime}ms</p>
            <p><strong>Memory Usage:</strong> ${performanceData.memoryUsage}MB</p>
        `;
  }
  validateSettings(settings) {
    return {
      valid: true,
      errors: [],
      warnings: []
    };
  }
  displayConfigValidation(container, validation) {
    container.style.display = 'block';
    container.className = 'test-results success';
    container.innerHTML = `<h4>✅ Configuration Valid</h4>`;
  }
  handleTestCompletion(data) {
    (window.logger?.info || console.log)('Test completed:', data);
  }
  handleTestFailure(data) {
    (window.logger?.error || console.error)('Test failed:', data);
  }
}
 
// Make testing functions globally available
window.openAPITestingDashboard = () => window.testingHub?.openAPITestingDashboard();
window.runQuickAPITests = () => window.testingHub?.runQuickAPITests();
window.testAllSubsystems = () => window.testingHub?.testAllSubsystems();
window.openSwaggerUI = () => window.testingHub?.openSwaggerUI();
window.validateSwaggerSpec = () => window.testingHub?.validateSwaggerSpec();
window.downloadSwaggerSpec = () => window.testingHub?.downloadSwaggerSpec();
window.testHistoryUI = () => window.testingHub?.testHistoryUI();
window.testLoggingUI = () => window.testingHub?.testLoggingUI();
window.testImportUI = () => window.testingHub?.testImportUI();
window.runAllUITests = () => window.testingHub?.runAllUITests();
window.runHealthChecks = () => window.testingHub?.runHealthChecks();
window.testConnectivity = () => window.testingHub?.testConnectivity();
window.checkPerformance = () => window.testingHub?.checkPerformance();
window.validateConfiguration = () => window.testingHub?.validateConfiguration();
window.testImportWorkflow = () => window.testingHub?.testImportWorkflow();
window.testExportWorkflow = () => window.testingHub?.testExportWorkflow();
window.testAuthFlow = () => window.testingHub?.testAuthFlow();
window.runE2ETests = () => window.testingHub?.runE2ETests();
window.clearAllTestResults = () => window.testingHub?.clearAllTestResults();
window.exportTestResults = () => window.testingHub?.exportTestResults();
var _default = exports.default = TestingHub;
 
},{}],82:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UIManager = void 0;
var _circularProgress = require("../../../public/js/modules/circular-progress.js");
var _elementRegistry = require("../../../public/js/modules/element-registry.js");
var _progressManager = _interopRequireDefault(require("../../../public/js/modules/progress-manager.js"));
var _errorTypes = require("../../../public/js/modules/error/error-types.js");
// File: ui-manager.js
// Description: UI management for PingOne user import tool
// 
// This module handles all user interface interactions and state management:
// - Status notifications and user feedback
// - Progress tracking and real-time updates
// - View transitions and navigation
// - Debug logging and error display
// - Connection status indicators
// - Form handling and validation feedback
// 
// Provides a centralized interface for updating the UI based on application events.
 
// Enable debug mode for development (set to false in production)
const DEBUG_MODE = process.env.NODE_ENV === 'development';
 
/**
 * UI Manager Class
 * 
 * Manages all user interface interactions and updates with centralized error handling.
 */
class UIManager {
  /**
   * Create a new UIManager instance
   * @param {Object} options - Configuration options
   * @param {Object} options.errorManager - Error manager instance
   * @param {Object} options.logger - Logger instance
   */
  constructor() {
    let {
      errorManager,
      logger
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    // Initialize logger from provided logger or fallback to console
    this.logger = logger ? logger.child({
      component: 'UIManager'
    }) : console;
 
    // Initialize error manager
    this.errorManager = errorManager || {
      handleError: (error, context) => {
        (window.logger?.error || console.error)('Unhandled error (no error manager):', error, context);
      }
    };
 
    // Initialize UI elements
    this.notificationContainer = null;
    this.progressContainer = null;
    this.tokenStatusElement = null;
    this.connectionStatusElement = null;
 
    // Initialize the UI manager
    this.initialize();
  }
 
  /**
   * Initialize UI manager and setup core functionality
   */
  /**
   * Initialize the UI Manager
   * @private
   */
  initialize() {
    try {
      this.setupElements();
      this.logger.info('UI Manager initialized successfully');
    } catch (error) {
      this.errorManager.handleError(error, {
        component: 'UIManager',
        operation: 'initialize',
        severity: 'error',
        context: {
          message: 'Failed to initialize UI Manager',
          error: error.message
        }
      });
    }
  }
 
  /**
   * Initialize UI manager (alias for initialize for compatibility)
   * @returns {Promise<void>} Promise that resolves when initialization is complete
   */
  async init() {
    this.initialize();
    return Promise.resolve();
  }
 
  /**
   * Setup UI elements and initialize core DOM references
   */
  setupElements() {
    try {
      // Initialize core UI elements with safe fallbacks
      this.notificationContainer = _elementRegistry.ElementRegistry.notificationContainer ? _elementRegistry.ElementRegistry.notificationContainer() : null;
      this.progressContainer = _elementRegistry.ElementRegistry.progressContainer ? _elementRegistry.ElementRegistry.progressContainer() : null;
      this.tokenStatusElement = _elementRegistry.ElementRegistry.tokenStatus ? _elementRegistry.ElementRegistry.tokenStatus() : null;
      this.connectionStatusElement = _elementRegistry.ElementRegistry.connectionStatus ? _elementRegistry.ElementRegistry.connectionStatus() : null;
 
      // Initialize navigation items for safe access
      this.navItems = document.querySelectorAll('[data-view]');
      if (!this.notificationContainer) {
        this.logger.warn('Notification container not found');
      }
      if (!this.progressContainer) {
        this.logger.warn('Progress container not found');
      }
      this.logger.debug('UI elements setup completed', {
        hasNotificationContainer: !!this.notificationContainer,
        hasProgressContainer: !!this.progressContainer,
        hasTokenStatusElement: !!this.tokenStatusElement,
        hasConnectionStatusElement: !!this.connectionStatusElement,
        navItemsCount: this.navItems ? this.navItems.length : 0
      });
    } catch (error) {
      this.logger.error('Error setting up UI elements', {
        error: error.message
      });
    }
  }
 
  /**
   * Show a status message in the status bar
   * @param {string} message - The message to display
   * @param {string} [type='info'] - Message type (info, success, warning, error)
   * @param {Object} [options] - Additional options
   * @param {number} [options.duration=5000] - Duration in milliseconds to show the message
   * @param {boolean} [options.autoDismiss=true] - Whether to auto-dismiss the message
   * @param {string} [options.errorId] - Unique error ID for tracking
   * @param {Object} [options.context] - Additional context for the message
   */
  /**
   * Show a status message in the status bar
   * @param {string} message - The message to display
   * @param {string} [type='info'] - Message type (info, success, warning, error)
   * @param {Object} [options] - Additional options
   * @param {number} [options.duration=5000] - Duration in milliseconds to show the message
   * @param {boolean} [options.autoDismiss=true] - Whether to auto-dismiss the message
   * @param {string} [options.errorId] - Unique error ID for tracking
   * @param {Object} [options.context] - Additional context for the message
   */
  showStatusBar(message) {
    let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const {
      duration = 5000,
      autoDismiss = true,
      errorId,
      context = {}
    } = options;
    try {
      // Log the status message with appropriate level
      const logLevel = {
        info: 'info',
        success: 'info',
        warning: 'warn',
        error: 'error'
      }[type] || 'log';
 
      // Create log context
      const logContext = {
        messageType: type,
        ...(errorId && {
          errorId
        }),
        ...context
      };
 
      // Log the message with context
      this.logger[logLevel](`Status: ${message}`, logContext);
 
      // If status bar element is not available, just log and return
      if (!this.statusBarElement) {
        this.logger.debug('Status bar element not available in current view', logContext);
        return;
      }
 
      // Clear any existing timers
      if (this.statusBarTimer) {
        clearTimeout(this.statusBarTimer);
        this.statusBarTimer = null;
      }
 
      // Clear existing content using Safe DOM
      const safeDOM = window.safeDOM || new SafeDOM(this.logger);
      const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
      const UI_CONFIG = window.UI_CONFIG || {
        CLASSES: {
          ERROR: 'error',
          SUCCESS: 'success'
        }
      };
      safeDOM.setHTML(this.statusBarElement, '');
 
      // Create message element using Safe DOM
      const msg = document.createElement('span');
      safeDOM.addClass(msg, 'status-message');
 
      // Add error ID to the message if available
      let displayMessage = message;
      if (type === UI_CONFIG.CLASSES.ERROR && errorId) {
        displayMessage += ` (Error ID: ${errorId})`;
 
        // In development, show more context for errors
        if (process.env.NODE_ENV === 'development' && Object.keys(context).length > 0) {
          displayMessage += `\n${JSON.stringify(context, null, 2)}`;
        }
      }
      safeDOM.setText(msg, displayMessage);
      this.statusBarElement.appendChild(msg);
 
      // Add dismiss button for error/warning (persistent messages)
      if (type === UI_CONFIG.CLASSES.ERROR || type === 'warning') {
        const dismiss = document.createElement('button');
        safeDOM.addClass(dismiss, 'status-dismiss');
        safeDOM.setHTML(dismiss, '&times;');
        dismiss.setAttribute('aria-label', 'Dismiss message');
 
        // Use error handler to wrap the event handler
        dismiss.onclick = errorHandler.wrapEventHandler(() => this.clearStatusBar(), 'Status bar dismiss button click');
        this.statusBarElement.appendChild(dismiss);
      }
 
      // Set status bar classes
      this.statusBarElement.className = `status-bar status-bar-${type} visible`;
 
      // Auto-dismiss for success/info messages or if explicitly enabled
      const shouldAutoDismiss = autoDismiss && (type === 'success' || type === 'info');
      if (shouldAutoDismiss) {
        this.statusBarTimer = setTimeout(() => {
          this.clearStatusBar();
        }, duration);
      }
    } catch (error) {
      // If there's an error showing the status bar, report it but don't crash
      this.errorManager.handleError(error, {
        component: 'UIManager',
        operation: 'showStatusBar',
        severity: 'warning',
        context: {
          originalMessage: message,
          type,
          options,
          errorMessage: error.message
        }
      });
 
      // Fallback to console if the error manager fails
      (window.logger?.error || console.error)('Failed to show status bar:', error);
      (window.logger?.debug || console.log)('Original message:', message);
 
      // Try to show a simplified error message
      try {
        if (this.statusBarElement) {
          this.statusBarElement.textContent = `Error: ${message.substring(0, 100)}`;
          this.statusBarElement.className = 'status-bar status-bar-error visible';
        }
      } catch (e) {
        // If we can't even show the error message, just give up
        (window.logger?.error || console.error)('Completely failed to show status bar:', e);
      }
    }
  }
 
  /**
   * Clear the status bar with smooth animation
   * @param {Object} [options] - Additional options
   * @param {boolean} [options.force=false] - Force clear without animation
   */
  clearStatusBar() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    try {
      // Clear any pending auto-dismiss timers
      if (this.statusBarTimer) {
        clearTimeout(this.statusBarTimer);
        this.statusBarTimer = null;
      }
 
      // If status bar element doesn't exist, just return
      if (!this.statusBarElement) {
        this.logger.debug('Status bar element not found during clear');
        return;
      }
      const {
        force = false
      } = options;
      const safeDOM = window.safeDOM || new SafeDOM(this.logger);
      const UI_CONFIG = window.UI_CONFIG || {
        TIMEOUTS: {
          ANIMATION: 300
        }
      };
      if (force) {
        // Immediate removal using Safe DOM
        safeDOM.setHTML(this.statusBarElement, '');
        this.statusBarElement.className = 'status-bar';
        this.logger.debug('Status bar cleared immediately');
      } else {
        // Animate out using Safe DOM
        safeDOM.removeClass(this.statusBarElement, 'visible');
 
        // Remove the element after animation completes
        setTimeout(() => {
          if (this.statusBarElement) {
            safeDOM.setHTML(this.statusBarElement, '');
            this.statusBarElement.className = 'status-bar';
          }
        }, UI_CONFIG.TIMEOUTS?.ANIMATION || 300); // Use config constant for timeout
 
        this.logger.debug('Status bar cleared with animation');
      }
    } catch (error) {
      this.errorManager.handleError(error, {
        component: 'UIManager',
        operation: 'clearStatusBar',
        severity: 'warning',
        context: {
          options,
          errorMessage: error.message
        }
      });
 
      // Fallback to direct DOM manipulation if possible
      try {
        if (this.statusBarElement) {
          this.statusBarElement.innerHTML = '';
          this.statusBarElement.className = 'status-bar';
        }
      } catch (e) {
        (window.logger?.error || console.error)('Failed to clear status bar:', e);
      }
    }
  }
 
  /**
   * Show a success message
   * @param {string} message - The success message to display
   * @param {Object} [details] - Additional details to log
   */
  showSuccess(message) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.showStatusBar(message, 'success');
    this.logger.info('Success message shown', {
      message,
      ...details
    });
  }
 
  /**
   * Show a warning message
   * @param {string} message - The warning message to display
   * @param {Object} [details] - Additional details to log
   */
  showWarning(message) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.showStatusBar(message, 'warning');
    this.logger.warn('Warning message shown', {
      message,
      ...details
    });
  }
 
  /**
   * Show an info message
   * @param {string} message - The info message to display
   * @param {Object} [details] - Additional details to log
   */
  showInfo(message) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.showStatusBar(message, 'info');
  }
  /**
   * Show an error message to the user
   * @param {string|Error} error - Error title, message, or Error object
   * @param {string|Object} [details] - Additional error details or options object
   * @param {Object} [options] - Additional options
   * @param {string} [options.errorId] - Unique error ID for tracking
   * @param {Object} [options.context] - Additional context for the error
   * @param {boolean} [options.reportToServer=true] - Whether to report the error to the server
   * @param {string} [options.operation] - The operation that failed
   * @param {string} [options.component] - The component where the error occurred
   */
  showError(error) {
    let details = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    // Handle different parameter patterns
    let errorMessage, errorObj, errorContext;
    if (error instanceof Error) {
      // First parameter is an Error object
      errorObj = error;
      errorMessage = error.message;
      errorContext = typeof details === 'object' && details !== null ? details : {};
    } else if (typeof error === 'string' && details instanceof Error) {
      // First is title, second is Error object
      errorObj = details;
      errorMessage = `${error}: ${details.message}`;
      errorContext = {};
    } else if (typeof error === 'string' && typeof details === 'string') {
      // Both are strings (title and message)
      errorMessage = `${error}: ${details}`;
      errorObj = new Error(errorMessage);
      errorObj.name = error;
      errorContext = {};
    } else if (typeof error === 'string') {
      // First is message, second is options
      errorMessage = error;
      errorObj = new Error(errorMessage);
      errorContext = typeof details === 'object' && details !== null ? details : {};
    } else {
      // Invalid parameters
      const invalidError = new Error('Invalid parameters passed to showError');
      this.errorManager.handleError(invalidError, {
        component: 'UIManager',
        operation: 'showError',
        severity: 'error',
        context: {
          error,
          details,
          options
        }
      });
      return;
    }
 
    // Merge contexts
    const mergedContext = {
      ...errorContext,
      ...options.context
    };
 
    // Report the error through the error manager
    if (options.reportToServer !== false) {
      this.errorManager.handleError(errorObj, {
        component: options.component || 'UIManager',
        operation: options.operation || 'showError',
        severity: 'error',
        context: mergedContext
      });
    }
 
    // Show the error in the UI
    this.showStatusBar(errorMessage, 'error', {
      autoDismiss: false,
      errorId: options.errorId,
      context: mergedContext,
      ...options
    });
 
    // Log the error with additional context
    this.logger.error('Error message shown', {
      error: errorMessage,
      name: errorObj.name,
      stack: errorObj.stack,
      ...mergedContext
    });
  }
  catch(error) {
    // If there's an error in the error handler, log to console
    (window.logger?.error || console.error)('Error in showError:', error);
 
    // Try to show a basic error message
    try {
      const fallbackMessage = 'An error occurred';
      this.showStatusBar(fallbackMessage, 'error', {
        autoDismiss: false,
        context: {
          originalError: error instanceof Error ? error.message : String(error),
          timestamp: new Date().toISOString()
        }
      });
    } catch (e) {
      // If we can't even show the error message, just give up
      (window.logger?.error || console.error)('Completely failed to show error:', e);
    }
  }
 
  /**
   * Hide loading indicator dand optionally show success message
   * @param {string} successMessage - Optional success message to show after hiding loading
   */
  hideLoading() {
    let successMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    this.clearStatusBar();
    if (successMessage) {
      this.showSuccess(successMessage);
    }
    this.logger.debug('Loading indicator hidden');
  }
 
  /**
   * Update progress bar with current and total values
   * @param {number} current - Current progress value
   * @param {number} total - Total progress value
   * @param {string} message - Progress message
   */
  updateProgress(current, total) {
    let message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] updateProgress() called with:', {
      current,
      total,
      message
    });
    if (!this.progressContainer) {
      (window.logger?.error || console.error)('🔍 [UI MANAGER DEBUG] Progress container not found in updateProgress');
      this.logger.warn('Progress container not found');
      return;
    }
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress container found, calculating percentage...');
    const percentage = total > 0 ? Math.round(current / total * 100) : 0;
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Calculated percentage:', percentage);
 
    // Initialize utilities for safe DOM operations
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        PROGRESS_BAR_FILL: '.progress-bar-fill',
        PROGRESS_PERCENTAGE: '.progress-percentage',
        PROGRESS_TEXT: '.progress-text'
      }
    };
 
    // Update progress bar using Safe DOM
    const progressBar = safeDOM.select(UI_CONFIG.SELECTORS.PROGRESS_BAR_FILL, this.progressContainer);
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress bar element:', progressBar);
    if (progressBar) {
      progressBar.style.width = `${percentage}%`;
      (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress bar updated to:', `${percentage}%`);
    } else {
      (window.logger?.error || console.error)('🔍 [UI MANAGER DEBUG] Progress bar element not found');
    }
 
    // Update percentage text using Safe DOM
    const percentageElement = safeDOM.select(UI_CONFIG.SELECTORS.PROGRESS_PERCENTAGE, this.progressContainer);
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Percentage element:', percentageElement);
    if (percentageElement) {
      safeDOM.setText(percentageElement, `${percentage}%`);
      (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Percentage text updated to:', `${percentage}%`);
    } else {
      (window.logger?.error || console.error)('🔍 [UI MANAGER DEBUG] Percentage element not found');
    }
 
    // Update progress text using Safe DOM
    const progressText = safeDOM.select(UI_CONFIG.SELECTORS.PROGRESS_TEXT, this.progressContainer);
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress text element:', progressText);
    if (progressText && message) {
      safeDOM.setText(progressText, message);
      (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress text updated to:', message);
    } else {
      (window.logger?.error || console.error)('🔍 [UI MANAGER DEBUG] Progress text element not found or no message');
    }
    this.logger.debug('Progress updated', {
      current,
      total,
      percentage,
      message
    });
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] updateProgress() completed');
  }
 
  /**
   * Update token status display
   * @param {string} status - Token status (valid, expired, etc.)
   * @param {string} message - Status message
   */
  updateTokenStatus(status) {
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    if (!this.tokenStatusElement) {
      this.logger.warn('Token status element not found');
      return;
    }
    this.tokenStatusElement.className = `token-status ${status}`;
    this.tokenStatusElement.textContent = message || status;
    this.logger.debug('Token status updated', {
      status,
      message
    });
  }
 
  /**
   * Update connection status display
   * @param {string} status - Connection status (connected, disconnected, etc.)
   * @param {string} message - Status message
   */
  updateConnectionStatus(status) {
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    if (!this.connectionStatusElement) {
      this.logger.warn('Connection status element not found');
      return;
    }
    this.connectionStatusElement.className = `connection-status ${status}`;
    this.connectionStatusElement.textContent = message || status;
    this.logger.debug('Connection status updated', {
      status,
      message
    });
  }
 
  /**
   * Show current token status with detailed information
   * @param {Object} tokenInfo - Token information object
   */
  showCurrentTokenStatus(tokenInfo) {
    if (!tokenInfo) {
      this.logger.warn('No token info provided');
      return;
    }
    const {
      isValid,
      expiresAt,
      timeRemaining
    } = tokenInfo;
    if (!isValid) {
      this.updateTokenStatus('expired', '');
      return;
    }
    const timeRemainingText = timeRemaining ? ` (${timeRemaining})` : '';
    this.updateTokenStatus('valid', `Token valid${timeRemainingText}`);
    this.logger.info('Current token status displayed', {
      isValid,
      expiresAt,
      timeRemaining
    });
  }
 
  /**
   * Update universal token status bar
   * @param {Object} tokenInfo - Token information object
   */
  updateUniversalTokenStatus(tokenInfo) {
    // Redirect to token-status-indicator instead of universal-token-status
    const tokenStatusBar = document.getElementById('token-status-indicator');
    if (!tokenStatusBar) {
      this.logger.warn('Token status indicator not found');
      return;
    }
    if (!tokenInfo) {
      tokenStatusBar.style.display = 'none';
      return;
    }
    const {
      isValid,
      expiresAt,
      timeRemaining
    } = tokenInfo;
    const statusContent = tokenStatusBar.querySelector('.token-status-content');
    if (statusContent) {
      const icon = statusContent.querySelector('.token-status-icon');
      const text = statusContent.querySelector('.token-status-text');
      const time = statusContent.querySelector('.token-status-time');
      if (isValid) {
        icon.textContent = '✅';
        text.textContent = 'Token valid';
        time.textContent = timeRemaining || '';
      } else {
        icon.textContent = '❌';
        text.textContent = '';
        text.style.visibility = 'hidden';
        time.textContent = '';
      }
    }
    tokenStatusBar.style.display = 'block';
    this.logger.debug('Token status indicator updated', {
      isValid,
      timeRemaining
    });
  }
 
  /**
   * Update home page token status
   * @param {boolean} isLoading - Whether to show loading state
   * @param {string} message - Status message
   */
  updateHomeTokenStatus() {
    let isLoading = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    const homeTokenStatus = document.getElementById('home-token-status');
    if (!homeTokenStatus) {
      (window.logger?.error || console.log)('❌ home-token-status element not found!');
      return;
    }
    (window.logger?.debug || console.log)('✅ Found home-token-status element:', homeTokenStatus);
 
    // Check current token status to determine button color
    let hasValidToken = false;
    let buttonClass = 'btn-danger'; // Default to red
    let buttonText = 'Get New Token';
    try {
      // First check for stashed token in localStorage
      hasValidToken = this.checkForStashedToken();
 
      // If no stashed token, check PingOne client
      if (!hasValidToken && window.app && window.app.pingOneClient) {
        const tokenInfo = window.app.pingOneClient.getCurrentTokenTimeRemaining();
        if (tokenInfo && tokenInfo.token && !tokenInfo.isExpired) {
          hasValidToken = true;
        }
      }
 
      // Set button appearance based on token status
      if (hasValidToken) {
        buttonClass = 'btn-success'; // Green when token is valid
        buttonText = 'Token Valid';
      }
    } catch (error) {
      (window.logger?.error || console.log)('Error checking token status:', error);
    }
 
    // Move to bottom of sidebar
    const sidebar = document.querySelector('.sidebar');
    if (sidebar && homeTokenStatus.parentNode !== sidebar) {
      sidebar.appendChild(homeTokenStatus);
      (window.logger?.debug || console.log)('✅ Moved home-token-status to bottom of sidebar');
    }
 
    // Add debug label to home-token-status container (red, above box)
    if (!document.getElementById('debug-home-token-status-label')) {
      const debugLabel = document.createElement('div');
      debugLabel.id = 'debug-home-token-status-label';
      debugLabel.style.cssText = `
                position: absolute !important;
                top: -30px !important;
                left: 0 !important;
                background: #ff0000 !important;
                color: #ffffff !important;
                padding: 4px 8px !important;
                font-size: 12px !important;
                font-weight: bold !important;
                border: 2px solid #000 !important;
                z-index: 9999 !important;
                white-space: nowrap !important;
                pointer-events: none !important;
            `;
      debugLabel.textContent = 'DEBUG: home-token-status CONTAINER';
 
      // Ensure container has relative positioning
      homeTokenStatus.style.cssText = `
                position: relative !important;
                background: #ffffcc !important;
                border: 1px solid #dee2e6 !important;
                border-radius: 6px !important;
                padding: 2px !important;
                width: fit-content !important;
                height: auto !important;
                display: block !important;
                overflow: visible !important;
                margin-top: auto !important;
            `;
      homeTokenStatus.appendChild(debugLabel);
      (window.logger?.debug || console.log)('✅ Added debug label to home-token-status container');
    }
    if (isLoading) {
      homeTokenStatus.innerHTML = '';
    } else {
      // Use the provided token-status-indicator markup with dynamic button color and enhanced styling
      homeTokenStatus.innerHTML = `
                <div id="token-status-indicator" class="token-status-indicator valid" role="status" aria-live="polite" style="display: block !important; padding: 0 !important; margin: 0 !important; background: none !important; border: none !important;">
                    <button id="get-token-btn" class="btn ${buttonClass}" style="font-size: 14px !important; padding: 8px 16px !important; margin: 0 !important; font-weight: 500 !important; border-radius: 6px !important; box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important; transition: all 0.2s ease !important;">
                        <i class="fas fa-key"></i> ${buttonText}
                    </button>
                </div>
            `;
      // Wire up the button to call getNewToken if available
      const getTokenBtn = document.getElementById('get-token-btn');
      if (getTokenBtn) {
        getTokenBtn.addEventListener('click', () => {
          if (window.tokenStatusIndicator && typeof window.tokenStatusIndicator.getNewToken === 'function') {
            window.tokenStatusIndicator.getNewToken();
          } else if (typeof this.getNewToken === 'function') {
            this.getNewToken();
          } else {
            // TODO: Refactor: Use Notification or Modal from UI subsystem instead of alert.
            // alert('Get New Token functionality is not available.');
          }
        });
      }
    }
    homeTokenStatus.style.display = 'block';
    this.logger.debug('Home token status updated', {
      isLoading,
      message,
      hasValidToken,
      buttonClass
    });
  }
 
  /**
   * Check for stashed token in localStorage
   * @returns {boolean} True if valid token is found
   */
  checkForStashedToken() {
    try {
      if (typeof localStorage === 'undefined') {
        return false;
      }
      const token = localStorage.getItem('pingone_worker_token');
      const expiry = localStorage.getItem('pingone_token_expiry');
      if (!token || !expiry) {
        return false;
      }
      const expiryTime = parseInt(expiry, 10);
      const now = Date.now();
 
      // Check if token is expired (with 5 minute buffer)
      if (isNaN(expiryTime) || now >= expiryTime - 5 * 60 * 1000) {
        return false;
      }
      return true;
    } catch (error) {
      (window.logger?.error || console.error)('Error checking for stashed token:', error);
      return false;
    }
  }
 
  /**
   * Update settings save status with message and type
   * @param {string} message - Status message
   * @param {string} type - Message type (success, error, warning, info)
   */
  updateSettingsSaveStatus(message) {
    let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
    const settingsStatus = document.querySelector('.settings-save-status');
    if (!settingsStatus) {
      this.logger.warn('Settings save status element not found');
      return;
    }
 
    // Update classes
    settingsStatus.className = `settings-save-status ${type} show`;
 
    // Create simple HTML structure with text on the left, icon on the right
    const iconClass = this.getStatusIcon(type);
    settingsStatus.innerHTML = `
            <span>${message}</span>
            <i class="fas ${iconClass}"></i>
        `;
 
    // Auto-hide success messages after 3 seconds
    if (type === 'success') {
      setTimeout(() => {
        settingsStatus.classList.remove('show');
      }, 3000);
    }
    this.logger.info('Settings save status updated', {
      message,
      type
    });
  }
 
  /**
   * Show settings action status with enhanced options
   * @param {string} message - Status message
   * @param {string} type - Message type (success, error, warning, info)
   * @param {Object} options - Additional display options
   * @param {boolean} options.autoDismiss - Whether to auto-dismiss
   * @param {number} options.duration - Duration before auto-dismiss
   */
  showSettingsActionStatus(message) {
    let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'info';
    let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const settingsActionStatus = document.getElementById('settings-action-status');
    if (!settingsActionStatus) {
      this.logger.warn('Settings action status element not found');
      return;
    }
 
    // Clear existing content
    settingsActionStatus.innerHTML = '';
    settingsActionStatus.className = `settings-action-status ${type}`;
 
    // Create status content
    const statusContent = document.createElement('div');
    statusContent.className = 'status-content';
    const text = document.createElement('span');
    text.textContent = message;
    statusContent.appendChild(text);
    const icon = document.createElement('i');
    icon.className = `fas ${this.getStatusIcon(type)}`;
    statusContent.appendChild(icon);
    settingsActionStatus.appendChild(statusContent);
    settingsActionStatus.style.display = 'block';
 
    // No auto-dismiss for any type
    this.logger.info('Settings action status shown', {
      message,
      type,
      autoDismiss: false
    });
  }
 
  /**
   * Get appropriate icon class for status type
   * @param {string} type - Status type
   * @returns {string} Icon class name
   */
  getStatusIcon(type) {
    const icons = {
      success: 'fa-check-circle',
      error: 'fa-times-circle',
      warning: 'fa-exclamation-triangle',
      info: 'fa-info-circle'
    };
    return icons[type] || icons.info;
  }
 
  /**
   * Hide settings action status
   */
  hideSettingsActionStatus() {
    const settingsActionStatus = document.getElementById('settings-action-status');
    if (settingsActionStatus) {
      settingsActionStatus.style.display = 'none';
      this.logger.debug('Settings action status hidden');
    }
  }
 
  /**
   * Show import status with operation details
   * @param {string} status - Import status
   * @param {string} message - Status message
   * @param {Object} details - Additional details
   */
  showImportStatus(status) {
    let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    let details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const importStatus = document.getElementById('import-status');
    if (!importStatus) {
      this.logger.warn('Import status element not found');
      return;
    }
    importStatus.style.display = 'block';
    importStatus.className = `import-status ${status}`;
    const statusText = importStatus.querySelector('.status-text');
    if (statusText) {
      statusText.textContent = message || status;
    }
    this.logger.info('Import status shown', {
      status,
      message,
      details
    });
  }
 
  /**
   * Clear all notifications from the UI
   */
  clearNotifications() {
    if (this.notificationContainer) {
      this.notificationContainer.innerHTML = '';
      this.logger.debug('All notifications cleared');
    }
    this.clearStatusBar();
  }
 
  /**
   * Hide progress display
   */
  hideProgress() {
    if (this.progressContainer) {
      const safeDOM = window.safeDOM || new SafeDOM(this.logger);
      safeDOM.hide(this.progressContainer);
      this.logger.debug('Progress display hidden');
    }
  }
 
  /**
   * Show progress section with enhanced debugging and fallback mechanisms
   */
  showProgress() {
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] showProgress() called');
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] this.progressContainer:', this.progressContainer);
 
    // Try multiple ways to get the progress container
    let progressContainer = this.progressContainer;
    if (!progressContainer) {
      (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress container not found in UI manager, trying direct access...');
      progressContainer = document.getElementById('progress-container');
    }
    if (!progressContainer) {
      (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress container not found by ID, trying ElementRegistry...');
      if (typeof _elementRegistry.ElementRegistry !== 'undefined' && _elementRegistry.ElementRegistry.progressContainer) {
        progressContainer = _elementRegistry.ElementRegistry.progressContainer();
      }
    }
    if (!progressContainer) {
      (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress container not found by ElementRegistry, trying class selector...');
      progressContainer = document.querySelector('.progress-container');
    }
    if (!progressContainer) {
      (window.logger?.error || console.error)('🔍 [UI MANAGER DEBUG] Progress container not found by any method');
      (window.logger?.error || console.error)('🔍 [UI MANAGER DEBUG] Available containers with "progress" in ID:', Array.from(document.querySelectorAll('[id*="progress"]')).map(el => el.id));
      (window.logger?.error || console.error)('🔍 [UI MANAGER DEBUG] Available containers with "progress" in class:', Array.from(document.querySelectorAll('[class*="progress"]')).map(el => ({
        id: el.id,
        className: el.className
      })));
      return;
    }
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Progress container found, showing...');
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Current display style:', progressContainer.style.display);
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Current visibility:', progressContainer.offsetParent !== null ? 'visible' : 'hidden');
 
    // Force show the progress container
    progressContainer.style.display = 'block';
    progressContainer.style.visibility = 'visible';
    progressContainer.style.opacity = '1';
 
    // Ensure it's not hidden by CSS
    progressContainer.classList.remove('hidden', 'd-none');
    progressContainer.classList.add('visible');
 
    // Force layout recalculation
    progressContainer.offsetHeight;
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Display style after setting to block:', progressContainer.style.display);
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Container visibility:', progressContainer.offsetParent !== null ? 'visible' : 'hidden');
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Container dimensions:', {
      offsetWidth: progressContainer.offsetWidth,
      offsetHeight: progressContainer.offsetHeight,
      clientWidth: progressContainer.clientWidth,
      clientHeight: progressContainer.clientHeight
    });
 
    // Scroll into view if needed
    if (progressContainer.offsetParent !== null) {
      progressContainer.scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
    }
 
    // Update UI manager's reference
    this.progressContainer = progressContainer;
    this.logger.debug('Progress display shown');
 
    // Additional verification
    setTimeout(() => {
      const isVisible = progressContainer.offsetParent !== null;
      const rect = progressContainer.getBoundingClientRect();
      (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Final verification:', {
        isVisible,
        dimensions: {
          width: rect.width,
          height: rect.height
        },
        display: progressContainer.style.display,
        computedDisplay: window.getComputedStyle(progressContainer).display
      });
    }, 100);
  }
 
  /**
   * Set button loading state
   * @param {string} buttonId - Button element ID
   * @param {boolean} isLoading - Whether to show loading state
   */
  setButtonLoading(buttonId, isLoading) {
    const button = document.getElementById(buttonId);
    if (!button) {
      // Don't log warning for buttons that are intentionally hidden or optional
      if (buttonId === 'get-token-quick') {
        this.logger.debug(`Button with ID '${buttonId}' not found (may be hidden)`);
      } else {
        this.logger.warn(`Button with ID '${buttonId}' not found`);
      }
      return;
    }
    if (isLoading) {
      button.disabled = true;
      button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Loading...';
      button.classList.add('loading');
    } else {
      button.disabled = false;
      button.innerHTML = button.getAttribute('data-original-text') || 'Submit';
      button.classList.remove('loading');
    }
    this.logger.debug('Button loading state updated', {
      buttonId,
      isLoading
    });
  }
 
  /**
   * Update population dropdown fields with available populations
   * @param {Array} populations - Array of population objects
   */
  updatePopulationFields(populations) {
    if (!populations || !Array.isArray(populations)) {
      this.logger.warn('Invalid populations data provided');
      return;
    }
    const populationSelects = document.querySelectorAll('select[id*="population"]');
    populationSelects.forEach(select => {
      // Store current selection
      const currentValue = select.value;
 
      // Clear existing options
      select.innerHTML = '';
 
      // Add default option
      const defaultOption = document.createElement('option');
      defaultOption.value = '';
      defaultOption.textContent = 'Select a population...';
      select.appendChild(defaultOption);
 
      // Add population options
      populations.forEach(population => {
        const option = document.createElement('option');
        option.value = population.id;
        option.textContent = population.name;
        select.appendChild(option);
      });
 
      // Restore selection if it still exists
      if (currentValue && select.querySelector(`option[value="${currentValue}"]`)) {
        select.value = currentValue;
      }
    });
    this.logger.info('Population fields updated', {
      populationCount: populations.length,
      selectCount: populationSelects.length
    });
  }
 
  /**
   * Show notification with enhanced options
   * @param {string} title - Notification title
   * @param {string} message - Notification message
   * @param {string} type - Notification type (success, error, warning, info)
   * @param {Object} options - Additional display options
   * @param {boolean} options.autoDismiss - Whether to auto-dismiss
   * @param {number} options.duration - Duration before auto-dismiss
   */
  showNotification(title, message) {
    let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'info';
    let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    if (!this.notificationContainer) {
      this.logger.warn('Notification container not found');
      return;
    }
 
    // Clear existing content
    this.notificationContainer.innerHTML = '';
 
    // Create status header content
    const statusContent = document.createElement('div');
    statusContent.className = 'status-content';
 
    // Add icon
    const icon = document.createElement('i');
    icon.className = `fas ${this.getStatusIcon(type)}`;
    statusContent.appendChild(icon);
 
    // Add text
    const text = document.createElement('span');
    if (title && message) {
      text.textContent = `${title}: ${message}`;
    } else {
      text.textContent = title || message;
    }
    statusContent.appendChild(text);
 
    // Add to container
    this.notificationContainer.appendChild(statusContent);
 
    // Auto-dismiss if specified (but keep persistent for success messages)
    const shouldAutoDismiss = options.autoDismiss !== false && type !== 'error' && type !== 'success';
    if (shouldAutoDismiss) {
      const duration = options.duration || 5000;
      setTimeout(() => {
        if (this.notificationContainer && this.notificationContainer.contains(statusContent)) {
          this.notificationContainer.innerHTML = '';
        }
      }, duration);
    }
    this.logger.info('Status header updated', {
      title,
      message,
      type,
      autoDismiss: shouldAutoDismiss
    });
  }
 
  /**
   * Update import progress with detailed statistics
   * @param {number} current - Current progress value
   * @param {number} total - Total progress value
   * @param {string} message - Progress message
   * @param {Object} counts - Statistics counts
   * @param {number} counts.processed - Number of processed items
   * @param {number} counts.success - Number of successful items
   * @param {number} counts.failed - Number of failed items
   * @param {number} counts.skipped - Number of skipped items
   * @param {string} populationName - Population name
   * @param {string} populationId - Population ID
   */
  updateImportProgress(current, total) {
    let message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
    let counts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    let populationName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
    let populationId = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : '';
    // Update main progress
    this.updateProgress(current, total, message);
 
    // Update statistics if provided
    if (counts && typeof counts === 'object') {
      Object.entries(counts).forEach(_ref => {
        let [key, value] = _ref;
        const statElement = document.querySelector(`.stat-value.${key}`);
        if (statElement) {
          statElement.textContent = value || 0;
        }
      });
    }
 
    // Update population information if provided
    if (populationName || populationId) {
      const populationElement = document.querySelector('.detail-value.population-info');
      if (populationElement) {
        populationElement.textContent = populationName || populationId || 'Unknown';
      }
    }
    this.logger.debug('Import progress updated', {
      current,
      total,
      message,
      counts,
      populationName,
      populationId
    });
  }
 
  /**
   * Start import operation with progress tracking
   * @param {Object} options - Operation options
   * @param {string} options.operationType - Type of operation
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   * @param {string} options.populationId - Population ID
   */
  startImportOperation() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] startImportOperation() called with options:', options);
    const {
      operationType,
      totalUsers,
      populationName,
      populationId
    } = options;
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] About to call showProgress()...');
    this.showProgress();
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] showProgress() completed');
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] About to call updateProgress()...');
    this.updateProgress(0, totalUsers || 0, 'Starting import operation...');
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] updateProgress() completed');
 
    // Update operation details
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Operation type element:', operationTypeElement);
    if (operationTypeElement) {
      operationTypeElement.textContent = operationType || 'Import';
      (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] Operation type updated to:', operationType || 'Import');
    } else {
      (window.logger?.error || console.error)('🔍 [UI MANAGER DEBUG] Operation type element not found');
    }
    this.logger.info('Import operation started', {
      operationType,
      totalUsers,
      populationName,
      populationId
    });
    (window.logger?.debug || console.log)('🔍 [UI MANAGER DEBUG] startImportOperation() completed');
  }
 
  /**
   * Update import operation with session ID
   * @param {string} sessionId - Session ID for tracking
   */
  updateImportOperationWithSessionId(sessionId) {
    if (!sessionId) {
      this.logger.warn('No session ID provided for import operation');
      return;
    }
    const sessionElement = document.querySelector('.detail-value.session-id');
    if (sessionElement) {
      sessionElement.textContent = sessionId;
    }
    this.logger.info('Import operation session ID updated', {
      sessionId
    });
  }
 
  /**
   * Start export operation with progress tracking
   * @param {Object} options - Operation options
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   */
  startExportOperation() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      totalUsers,
      populationName
    } = options;
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Starting export operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Export';
    }
    this.logger.info('Export operation started', {
      totalUsers,
      populationName
    });
  }
 
  /**
   * Start delete operation with progress tracking
   * @param {Object} options - Operation options
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   */
  startDeleteOperation() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      totalUsers,
      populationName
    } = options;
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Starting delete operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Delete';
    }
    this.logger.info('Delete operation started', {
      totalUsers,
      populationName
    });
  }
 
  /**
   * Start modify operation with progress tracking
   * @param {Object} options - Operation options
   * @param {number} options.totalUsers - Total number of users
   * @param {string} options.populationName - Population name
   */
  startModifyOperation() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      totalUsers,
      populationName
    } = options;
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Starting modify operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Modify';
    }
    this.logger.info('Modify operation started', {
      totalUsers,
      populationName
    });
  }
 
  /**
   * Complete operation with results
   * @param {Object} results - Operation results
   * @param {number} results.processed - Number of processed items
   * @param {number} results.success - Number of successful items
   * @param {number} results.failed - Number of failed items
   * @param {number} results.skipped - Number of skipped items
   */
  completeOperation() {
    let results = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      processed,
      success,
      failed,
      skipped
    } = results;
    this.updateProgress(processed || 0, processed || 0, 'Operation completed');
 
    // Show completion message
    const message = `Operation completed: ${success || 0} successful, ${failed || 0} failed, ${skipped || 0} skipped`;
    this.showSuccess(message);
 
    // Hide progress after delay
    setTimeout(() => {
      this.hideProgress();
    }, 2000);
    this.logger.info('Operation completed', {
      processed,
      success,
      failed,
      skipped
    });
  }
 
  /**
   * Handle duplicate users with decision callback
   * @param {Array} duplicates - Array of duplicate user objects
   * @param {Function} onDecision - Callback function for user decision
   */
  handleDuplicateUsers(duplicates, onDecision) {
    if (!duplicates || duplicates.length === 0) {
      this.logger.warn('No duplicates provided for handling');
      return;
    }
    const message = `Found ${duplicates.length} duplicate users. How would you like to proceed?`;
    this.showWarning(message);
 
    // In a real implementation, you would show a modal or dialog here
    // For now, we'll just log the decision
    this.logger.info('Duplicate users found', {
      count: duplicates.length
    });
    if (onDecision && typeof onDecision === 'function') {
      onDecision('skip'); // Default to skip
    }
  }
 
  /**
   * Debug logging for development
   * @param {string} area - Debug area
   * @param {string} message - Debug message
   */
  debugLog(area, message) {
    if (DEBUG_MODE) {
      this.logger.debug(`[${area}] ${message}`);
    }
  }
 
  /**
   * Show status message with type
   * @param {string} type - Message type
   * @param {string} message - Message content
   * @param {string} details - Additional details
   */
  showStatusMessage(type, message) {
    let details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
    const fullMessage = details ? `${message}: ${details}` : message;
    this.showNotification('Status Update', fullMessage, type);
  }
 
  /**
   * Show export status
   */
  showExportStatus() {
    this.showProgress();
    this.updateProgress(0, 100, 'Preparing export...');
    this.logger.info('Export status shown');
  }
 
  /**
   * Update export progress
   * @param {number} current - Current progress
   * @param {number} total - Total progress
   * @param {string} message - Progress message
   * @param {Object} counts - Statistics counts
   */
  updateExportProgress(current, total, message) {
    let counts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    this.updateProgress(current, total, message);
 
    // Update export-specific statistics
    if (counts && typeof counts === 'object') {
      Object.entries(counts).forEach(_ref2 => {
        let [key, value] = _ref2;
        const statElement = document.querySelector(`.stat-value.${key}`);
        if (statElement) {
          statElement.textContent = value || 0;
        }
      });
    }
    this.logger.debug('Export progress updated', {
      current,
      total,
      message,
      counts
    });
  }
 
  /**
   * Show delete status
   * @param {number} totalUsers - Total number of users
   * @param {string} populationName - Population name
   * @param {string} populationId - Population ID
   */
  showDeleteStatus(totalUsers, populationName, populationId) {
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Preparing delete operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Delete';
    }
    this.logger.info('Delete status shown', {
      totalUsers,
      populationName,
      populationId
    });
  }
 
  /**
   * Update delete progress
   * @param {number} current - Current progress
   * @param {number} total - Total progress
   * @param {string} message - Progress message
   * @param {Object} counts - Statistics counts
   * @param {string} populationName - Population name
   * @param {string} populationId - Population ID
   */
  updateDeleteProgress(current, total, message) {
    let counts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    let populationName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
    let populationId = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : '';
    this.updateProgress(current, total, message);
 
    // Update delete-specific statistics
    if (counts && typeof counts === 'object') {
      Object.entries(counts).forEach(_ref3 => {
        let [key, value] = _ref3;
        const statElement = document.querySelector(`.stat-value.${key}`);
        if (statElement) {
          statElement.textContent = value || 0;
        }
      });
    }
    this.logger.debug('Delete progress updated', {
      current,
      total,
      message,
      counts,
      populationName,
      populationId
    });
  }
 
  /**
   * Show modify status
   * @param {number} totalUsers - Total number of users
   */
  showModifyStatus(totalUsers) {
    this.showProgress();
    this.updateProgress(0, totalUsers || 0, 'Preparing modify operation...');
    const operationTypeElement = document.querySelector('.detail-value.operation-type');
    if (operationTypeElement) {
      operationTypeElement.textContent = 'Modify';
    }
    this.logger.info('Modify status shown', {
      totalUsers
    });
  }
 
  /**
   * Update modify progress
   * @param {number} current - Current progress
   * @param {number} total - Total progress
   * @param {string} message - Progress message
   * @param {Object} counts - Statistics counts
   */
  updateModifyProgress(current, total, message) {
    let counts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    this.updateProgress(current, total, message);
 
    // Update modify-specific statistics
    if (counts && typeof counts === 'object') {
      Object.entries(counts).forEach(_ref4 => {
        let [key, value] = _ref4;
        const statElement = document.querySelector(`.stat-value.${key}`);
        if (statElement) {
          statElement.textContent = value || 0;
        }
      });
    }
    this.logger.debug('Modify progress updated', {
      current,
      total,
      message,
      counts
    });
  }
}
 
// Export the UIManager class
exports.UIManager = UIManager;
 
}).call(this)}).call(this,require('_process'))
},{"../../../public/js/modules/circular-progress.js":43,"../../../public/js/modules/element-registry.js":47,"../../../public/js/modules/error/error-types.js":48,"../../../public/js/modules/progress-manager.js":59,"@babel/runtime/helpers/interopRequireDefault":2,"_process":29}],83:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AdvancedRealtimeSubsystem = void 0;
/**
 * Advanced Real-time Features Subsystem
 * 
 * Provides advanced real-time capabilities including:
 * - Multi-user collaboration and presence
 * - Live progress sharing across sessions
 * - Real-time notifications and alerts
 * - Collaborative operation management
 * - Live analytics and metrics streaming
 * - Cross-session synchronization
 */
 
class AdvancedRealtimeSubsystem {
  constructor(logger, eventBus, realtimeCommunication, sessionSubsystem, progressSubsystem) {
    this.logger = logger;
    this.eventBus = eventBus;
    this.realtimeCommunication = realtimeCommunication;
    this.sessionSubsystem = sessionSubsystem;
    this.progressSubsystem = progressSubsystem;
 
    // Multi-user state management
    this.activeUsers = new Map();
    this.collaborationRooms = new Map();
    this.sharedOperations = new Map();
 
    // Real-time features state
    this.liveProgressStreams = new Map();
    this.notificationQueues = new Map();
    this.analyticsStreams = new Map();
 
    // Configuration
    this.config = {
      maxUsersPerRoom: 10,
      progressUpdateInterval: 1000,
      presenceUpdateInterval: 5000,
      notificationRetention: 100,
      analyticsBufferSize: 1000
    };
    this.logger.info('Advanced Real-time Features Subsystem initialized');
  }
 
  /**
   * Initialize the advanced real-time subsystem
   */
  async init() {
    try {
      // Set up EventBus listeners for real-time coordination
      this.setupEventBusListeners();
 
      // Initialize multi-user presence system
      await this.initializePresenceSystem();
 
      // Set up live progress sharing
      await this.initializeLiveProgressSharing();
 
      // Initialize real-time notifications
      await this.initializeNotificationSystem();
 
      // Set up collaborative operation management
      await this.initializeCollaborativeOperations();
 
      // Initialize live analytics streaming
      await this.initializeLiveAnalytics();
      this.logger.info('Advanced Real-time Features Subsystem initialized successfully');
      this.eventBus.emit('subsystem:ready', {
        subsystem: 'advanced-realtime'
      });
    } catch (error) {
      this.logger.error('Failed to initialize Advanced Real-time Features Subsystem', error);
      this.eventBus.emit('subsystem:error', {
        subsystem: 'advanced-realtime',
        error
      });
      throw error;
    }
  }
 
  /**
   * Set up EventBus listeners for real-time coordination
   */
  setupEventBusListeners() {
    this.logger.debug('Setting up EventBus listeners for advanced real-time features');
 
    // User session events
    this.eventBus.on('session:user-joined', data => this.handleUserJoined(data));
    this.eventBus.on('session:user-left', data => this.handleUserLeft(data));
    this.eventBus.on('session:activity-update', data => this.handleActivityUpdate(data));
 
    // Operation events for collaboration
    this.eventBus.on('operation:started', data => this.handleOperationStarted(data));
    this.eventBus.on('operation:progress', data => this.handleOperationProgress(data));
    this.eventBus.on('operation:completed', data => this.handleOperationCompleted(data));
    this.eventBus.on('operation:failed', data => this.handleOperationFailed(data));
 
    // Progress events for live sharing
    this.eventBus.on('progress:updated', data => this.handleProgressUpdate(data));
    this.eventBus.on('progress:milestone', data => this.handleProgressMilestone(data));
 
    // Analytics events for live streaming
    this.eventBus.on('analytics:metric-update', data => this.handleAnalyticsUpdate(data));
    this.eventBus.on('analytics:performance-data', data => this.handlePerformanceData(data));
    this.logger.debug('EventBus listeners set up for advanced real-time features');
  }
 
  /**
   * Initialize multi-user presence system
   */
  async initializePresenceSystem() {
    this.logger.debug('Initializing multi-user presence system');
 
    // Set up presence broadcasting
    this.presenceInterval = setInterval(() => {
      this.broadcastPresence();
    }, this.config.presenceUpdateInterval);
 
    // Listen for presence updates from other users
    this.realtimeCommunication.on('user-presence', data => {
      this.handlePresenceUpdate(data);
    });
 
    // Handle user connection/disconnection
    this.realtimeCommunication.on('user-connected', data => {
      this.handleUserConnected(data);
    });
    this.realtimeCommunication.on('user-disconnected', data => {
      this.handleUserDisconnected(data);
    });
    this.logger.debug('Multi-user presence system initialized');
  }
 
  /**
   * Initialize live progress sharing
   */
  async initializeLiveProgressSharing() {
    this.logger.debug('Initializing live progress sharing');
 
    // Set up progress streaming
    this.progressInterval = setInterval(() => {
      this.streamProgressUpdates();
    }, this.config.progressUpdateInterval);
 
    // Listen for shared progress updates
    this.realtimeCommunication.on('progress-update', data => {
      this.handleSharedProgressUpdate(data);
    });
 
    // Handle progress synchronization requests
    this.realtimeCommunication.on('progress-sync-request', data => {
      this.handleProgressSyncRequest(data);
    });
    this.logger.debug('Live progress sharing initialized');
  }
 
  /**
   * Broadcast presence to connected users
   */
  broadcastPresence() {
    try {
      if (!this.currentRoom || !this.currentUser) {
        return;
      }
      const presenceData = {
        roomId: this.currentRoom,
        userId: this.currentUser.id || 'anonymous',
        userName: this.currentUser.name || 'Anonymous User',
        status: 'active',
        lastActivity: new Date().toISOString(),
        timestamp: new Date().toISOString()
      };
 
      // Broadcast presence to room
      this.realtimeCommunication.emit('user-presence', presenceData);
 
      // Update local presence
      this.activeUsers.set(presenceData.userId, {
        ...presenceData,
        joinedAt: this.activeUsers.get(presenceData.userId)?.joinedAt || new Date()
      });
 
      // Emit local event for UI updates
      this.eventBus.emit('realtime:presence-broadcasted', presenceData);
      this.logger.debug('Presence broadcasted', {
        roomId: this.currentRoom,
        userId: presenceData.userId
      });
    } catch (error) {
      this.logger.error('Failed to broadcast presence', error);
    }
  }
 
  /**
   * Stream progress updates to connected users
   */
  streamProgressUpdates() {
    try {
      if (!this.currentRoom || !this.progressSubsystem) {
        return;
      }
 
      // Get current progress from progress subsystem
      const progressData = this.progressSubsystem.getCurrentProgress();
      if (progressData && progressData.isActive) {
        const updateData = {
          roomId: this.currentRoom,
          userId: this.currentUser?.id || 'anonymous',
          userName: this.currentUser?.name || 'Anonymous User',
          progress: {
            operationType: progressData.operationType,
            percentage: progressData.percentage,
            currentStep: progressData.currentStep,
            totalSteps: progressData.totalSteps,
            message: progressData.message,
            timestamp: new Date().toISOString()
          }
        };
 
        // Broadcast progress update to room
        this.realtimeCommunication.emit('progress-update', updateData);
 
        // Update local shared progress
        this.sharedProgress.set(updateData.userId, updateData.progress);
 
        // Emit local event for UI updates
        this.eventBus.emit('realtime:progress-streamed', updateData);
        this.logger.debug('Progress update streamed', {
          roomId: this.currentRoom,
          userId: updateData.userId,
          percentage: progressData.percentage
        });
      }
    } catch (error) {
      this.logger.error('Failed to stream progress updates', error);
    }
  }
 
  /**
   * Initialize real-time notification system
   */
  async initializeNotificationSystem() {
    this.logger.debug('Initializing real-time notification system');
 
    // Listen for notification events
    this.realtimeCommunication.on('notification', data => {
      this.handleIncomingNotification(data);
    });
 
    // Set up notification broadcasting
    this.eventBus.on('notification:send', data => {
      this.broadcastNotification(data);
    });
    this.logger.debug('Real-time notification system initialized');
  }
 
  /**
   * Initialize collaborative operation management
   */
  async initializeCollaborativeOperations() {
    this.logger.debug('Initializing collaborative operation management');
 
    // Listen for collaborative operation events
    this.realtimeCommunication.on('operation-request', data => {
      this.handleOperationRequest(data);
    });
    this.realtimeCommunication.on('operation-lock', data => {
      this.handleOperationLock(data);
    });
    this.realtimeCommunication.on('operation-unlock', data => {
      this.handleOperationUnlock(data);
    });
    this.logger.debug('Collaborative operation management initialized');
  }
 
  /**
   * Initialize live analytics streaming
   */
  async initializeLiveAnalytics() {
    this.logger.debug('Initializing live analytics streaming');
 
    // Set up analytics data streaming
    this.analyticsInterval = setInterval(() => {
      this.streamAnalyticsData();
    }, 5000); // Stream analytics every 5 seconds
 
    // Listen for analytics updates from other sessions
    this.realtimeCommunication.on('analytics-update', data => {
      this.handleAnalyticsStreamUpdate(data);
    });
    this.logger.debug('Live analytics streaming initialized');
  }
 
  /**
   * Stream analytics data to connected users
   */
  streamAnalyticsData() {
    try {
      if (!this.currentRoom || !this.analyticsDashboard) {
        return;
      }
 
      // Get current analytics data from analytics dashboard subsystem
      const analyticsData = this.analyticsDashboard.getAnalyticsDashboardData('5m');
      if (analyticsData) {
        const streamData = {
          roomId: this.currentRoom,
          userId: this.currentUser?.id || 'anonymous',
          analytics: {
            systemMetrics: analyticsData.systemMetrics,
            operationSummary: analyticsData.operationSummary,
            recentActivity: analyticsData.recentActivity?.slice(0, 5),
            // Last 5 activities
            timestamp: new Date().toISOString()
          }
        };
 
        // Broadcast analytics update to room
        this.realtimeCommunication.emit('analytics-update', streamData);
 
        // Emit local event for UI updates
        this.eventBus.emit('realtime:analytics-streamed', streamData);
        this.logger.debug('Analytics data streamed', {
          roomId: this.currentRoom,
          userId: streamData.userId,
          metricsCount: Object.keys(streamData.analytics.systemMetrics || {}).length
        });
      }
    } catch (error) {
      this.logger.error('Failed to stream analytics data', error);
    }
  }
 
  /**
   * Join a collaboration room
   */
  async joinCollaborationRoom(roomId, userInfo) {
    this.logger.info('Joining collaboration room', {
      roomId,
      userId: userInfo.id
    });
    try {
      // Check room capacity
      if (this.collaborationRooms.has(roomId)) {
        const room = this.collaborationRooms.get(roomId);
        if (room.users.size >= this.config.maxUsersPerRoom) {
          throw new Error('Collaboration room is at capacity');
        }
      } else {
        // Create new room
        this.collaborationRooms.set(roomId, {
          id: roomId,
          users: new Map(),
          operations: new Map(),
          createdAt: new Date(),
          lastActivity: new Date()
        });
      }
      const room = this.collaborationRooms.get(roomId);
      room.users.set(userInfo.id, {
        ...userInfo,
        joinedAt: new Date(),
        lastSeen: new Date(),
        isActive: true
      });
 
      // Broadcast user joined event
      this.broadcastToRoom(roomId, 'user-joined', {
        roomId,
        user: userInfo,
        totalUsers: room.users.size
      });
 
      // Send room state to new user
      this.sendToUser(userInfo.id, 'room-state', {
        roomId,
        users: Array.from(room.users.values()),
        operations: Array.from(room.operations.values())
      });
      this.eventBus.emit('collaboration:user-joined', {
        roomId,
        user: userInfo
      });
      return {
        success: true,
        roomId,
        userCount: room.users.size,
        users: Array.from(room.users.values())
      };
    } catch (error) {
      this.logger.error('Failed to join collaboration room', {
        roomId,
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Leave a collaboration room
   */
  async leaveCollaborationRoom(roomId, userId) {
    this.logger.info('Leaving collaboration room', {
      roomId,
      userId
    });
    try {
      if (!this.collaborationRooms.has(roomId)) {
        return {
          success: true,
          message: 'Room does not exist'
        };
      }
      const room = this.collaborationRooms.get(roomId);
      const user = room.users.get(userId);
      if (user) {
        room.users.delete(userId);
 
        // Broadcast user left event
        this.broadcastToRoom(roomId, 'user-left', {
          roomId,
          userId,
          user,
          totalUsers: room.users.size
        });
 
        // Clean up empty rooms
        if (room.users.size === 0) {
          this.collaborationRooms.delete(roomId);
          this.logger.debug('Removed empty collaboration room', {
            roomId
          });
        }
        this.eventBus.emit('collaboration:user-left', {
          roomId,
          userId,
          user
        });
      }
      return {
        success: true,
        roomId,
        userCount: room.users.size
      };
    } catch (error) {
      this.logger.error('Failed to leave collaboration room', {
        roomId,
        userId,
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Start live progress sharing for an operation
   */
  async startLiveProgressSharing(operationId) {
    let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.logger.info('Starting live progress sharing', {
      operationId
    });
    try {
      const progressStream = {
        operationId,
        startTime: new Date(),
        lastUpdate: new Date(),
        subscribers: new Set(),
        config: {
          updateInterval: config.updateInterval || this.config.progressUpdateInterval,
          includeMetrics: config.includeMetrics || true,
          includeErrors: config.includeErrors || true,
          maxHistory: config.maxHistory || 100
        },
        history: [],
        currentProgress: {
          percentage: 0,
          stage: 'initializing',
          message: 'Starting operation...',
          metrics: {}
        }
      };
      this.liveProgressStreams.set(operationId, progressStream);
 
      // Broadcast progress sharing started
      this.broadcastProgressEvent('progress-sharing-started', {
        operationId,
        config: progressStream.config
      });
      this.eventBus.emit('progress-sharing:started', {
        operationId,
        config: progressStream.config
      });
      return {
        success: true,
        operationId,
        streamId: operationId
      };
    } catch (error) {
      this.logger.error('Failed to start live progress sharing', {
        operationId,
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Subscribe to live progress updates
   */
  async subscribeLiveProgress(operationId, subscriberId) {
    this.logger.debug('Subscribing to live progress', {
      operationId,
      subscriberId
    });
    if (!this.liveProgressStreams.has(operationId)) {
      throw new Error(`Progress stream not found for operation: ${operationId}`);
    }
    const stream = this.liveProgressStreams.get(operationId);
    stream.subscribers.add(subscriberId);
 
    // Send current progress state to new subscriber
    this.sendProgressUpdate(subscriberId, {
      operationId,
      progress: stream.currentProgress,
      history: stream.history.slice(-10) // Send last 10 updates
    });
    this.logger.debug('Subscribed to live progress', {
      operationId,
      subscriberId,
      totalSubscribers: stream.subscribers.size
    });
    return {
      success: true,
      operationId,
      subscriberId
    };
  }
 
  /**
   * Send real-time notification
   */
  async sendRealtimeNotification(notification) {
    this.logger.debug('Sending real-time notification', {
      type: notification.type,
      recipients: notification.recipients?.length
    });
    try {
      const notificationData = {
        id: this.generateId(),
        timestamp: new Date(),
        ...notification
      };
 
      // Store in notification queues for recipients
      if (notification.recipients) {
        notification.recipients.forEach(recipientId => {
          if (!this.notificationQueues.has(recipientId)) {
            this.notificationQueues.set(recipientId, []);
          }
          const queue = this.notificationQueues.get(recipientId);
          queue.push(notificationData);
 
          // Maintain queue size
          if (queue.length > this.config.notificationRetention) {
            queue.shift();
          }
        });
      }
 
      // Broadcast notification
      this.broadcastNotification(notificationData);
      this.eventBus.emit('notification:sent', notificationData);
      return {
        success: true,
        notificationId: notificationData.id
      };
    } catch (error) {
      this.logger.error('Failed to send real-time notification', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Get live analytics dashboard data
   */
  async getLiveAnalyticsDashboard() {
    this.logger.debug('Getting live analytics dashboard data');
    try {
      const dashboardData = {
        timestamp: new Date(),
        activeUsers: this.activeUsers.size,
        collaborationRooms: this.collaborationRooms.size,
        liveProgressStreams: this.liveProgressStreams.size,
        totalNotifications: Array.from(this.notificationQueues.values()).reduce((sum, queue) => sum + queue.length, 0),
        connectionStatus: this.realtimeCommunication.getConnectionStatus(),
        systemMetrics: await this.getSystemMetrics(),
        operationMetrics: await this.getOperationMetrics(),
        userActivity: await this.getUserActivityMetrics()
      };
      return dashboardData;
    } catch (error) {
      this.logger.error('Failed to get live analytics dashboard data', {
        error: error.message
      });
      throw error;
    }
  }
 
  // Event Handlers
 
  handleUserJoined(data) {
    this.logger.debug('Handling user joined event', data);
    this.activeUsers.set(data.userId, {
      ...data,
      joinedAt: new Date(),
      lastActivity: new Date()
    });
    this.broadcastPresenceUpdate();
  }
  handleUserLeft(data) {
    this.logger.debug('Handling user left event', data);
    this.activeUsers.delete(data.userId);
    this.broadcastPresenceUpdate();
  }
  handleOperationStarted(data) {
    this.logger.debug('Handling operation started event', data);
    if (data.shareProgress) {
      this.startLiveProgressSharing(data.operationId, data.progressConfig);
    }
  }
  handleOperationProgress(data) {
    this.logger.debug('Handling operation progress event', data);
    if (this.liveProgressStreams.has(data.operationId)) {
      this.updateLiveProgress(data.operationId, data.progress);
    }
  }
  handleProgressUpdate(data) {
    this.logger.debug('Handling progress update event', data);
    this.streamProgressUpdate(data);
  }
 
  // Utility Methods
 
  broadcastToRoom(roomId, event, data) {
    if (this.collaborationRooms.has(roomId)) {
      const room = this.collaborationRooms.get(roomId);
      room.users.forEach((user, userId) => {
        this.sendToUser(userId, event, data);
      });
    }
  }
  sendToUser(userId, event, data) {
    // Send via real-time communication
    if (this.realtimeCommunication.isConnected) {
      this.realtimeCommunication.socket?.emit('user-message', {
        targetUserId: userId,
        event,
        data
      });
    }
  }
  broadcastPresenceUpdate() {
    const presenceData = {
      activeUsers: Array.from(this.activeUsers.values()),
      timestamp: new Date()
    };
    this.realtimeCommunication.socket?.emit('presence-update', presenceData);
    this.eventBus.emit('presence:updated', presenceData);
  }
  streamProgressUpdate(progressData) {
    this.realtimeCommunication.socket?.emit('progress-stream', progressData);
    this.eventBus.emit('progress-stream:update', progressData);
  }
  broadcastNotification(notification) {
    this.realtimeCommunication.socket?.emit('notification-broadcast', notification);
  }
  generateId() {
    return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
  async getSystemMetrics() {
    return {
      memoryUsage: performance.memory ? {
        used: performance.memory.usedJSHeapSize,
        total: performance.memory.totalJSHeapSize,
        limit: performance.memory.jsHeapSizeLimit
      } : null,
      connectionLatency: await this.measureConnectionLatency(),
      timestamp: new Date()
    };
  }
  async getOperationMetrics() {
    return {
      activeOperations: this.liveProgressStreams.size,
      completedOperations: 0,
      // Would be tracked elsewhere
      failedOperations: 0,
      // Would be tracked elsewhere
      averageOperationTime: 0,
      // Would be calculated from history
      timestamp: new Date()
    };
  }
  async getUserActivityMetrics() {
    return {
      activeUsers: this.activeUsers.size,
      totalSessions: this.sessionSubsystem ? await this.sessionSubsystem.getActiveSessionCount() : 0,
      averageSessionDuration: 0,
      // Would be calculated from session data
      timestamp: new Date()
    };
  }
  async measureConnectionLatency() {
    if (!this.realtimeCommunication.isConnected) return null;
    const start = performance.now();
    return new Promise(resolve => {
      this.realtimeCommunication.socket?.emit('ping', start, response => {
        const latency = performance.now() - start;
        resolve(latency);
      });
 
      // Timeout after 5 seconds
      setTimeout(() => resolve(null), 5000);
    });
  }
 
  /**
   * Cleanup and disconnect
   */
  async disconnect() {
    this.logger.info('Disconnecting Advanced Real-time Features Subsystem');
 
    // Clear intervals
    if (this.presenceInterval) clearInterval(this.presenceInterval);
    if (this.progressInterval) clearInterval(this.progressInterval);
    if (this.analyticsInterval) clearInterval(this.analyticsInterval);
 
    // Clear all data structures
    this.activeUsers.clear();
    this.collaborationRooms.clear();
    this.sharedOperations.clear();
    this.liveProgressStreams.clear();
    this.notificationQueues.clear();
    this.analyticsStreams.clear();
    this.logger.info('Advanced Real-time Features Subsystem disconnected');
  }
 
  /**
   * Get subsystem status
   */
  getStatus() {
    return {
      isInitialized: true,
      activeUsers: this.activeUsers.size,
      collaborationRooms: this.collaborationRooms.size,
      liveProgressStreams: this.liveProgressStreams.size,
      connectionStatus: this.realtimeCommunication.getConnectionStatus(),
      timestamp: new Date()
    };
  }
}
exports.AdvancedRealtimeSubsystem = AdvancedRealtimeSubsystem;
 
},{}],84:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AnalyticsDashboardSubsystem = void 0;
/**
 * Analytics Dashboard Subsystem
 * 
 * Provides comprehensive analytics and metrics collection including:
 * - Real-time system performance monitoring
 * - Operation analytics and insights
 * - User activity and collaboration metrics
 * - Historical trend analysis
 * - Resource usage tracking
 * - Performance benchmarking
 */
 
class AnalyticsDashboardSubsystem {
  constructor(logger, eventBus, advancedRealtimeSubsystem, progressSubsystem, sessionSubsystem) {
    this.logger = logger;
    this.eventBus = eventBus;
    this.advancedRealtime = advancedRealtimeSubsystem;
    this.progressSubsystem = progressSubsystem;
    this.sessionSubsystem = sessionSubsystem;
 
    // Analytics data storage
    this.metrics = {
      system: {
        performance: [],
        resources: [],
        connections: [],
        errors: []
      },
      operations: {
        imports: [],
        exports: [],
        modifications: [],
        deletions: []
      },
      users: {
        sessions: [],
        activity: [],
        collaboration: []
      },
      realtime: {
        connections: [],
        messages: [],
        latency: []
      }
    };
 
    // Configuration
    this.config = {
      metricsRetention: 24 * 60 * 60 * 1000,
      // 24 hours
      samplingInterval: 5 * 60 * 1000,
      // 5 minutes for main updates
      quickSamplingInterval: 30 * 1000,
      // 30 seconds for quick updates
      batchSize: 100,
      maxDataPoints: 1000,
      alertThresholds: {
        memoryUsage: 0.8,
        connectionLatency: 1000,
        errorRate: 0.05,
        operationFailureRate: 0.1
      }
    };
 
    // Session tracking
    this.sessionStart = Date.now();
    this.lastActivity = Date.now();
    this.activityHistory = [];
    this.performanceBaseline = null;
 
    // State management
    this.isCollecting = false;
    this.collectionInterval = null;
    this.alertsEnabled = true;
    this.dashboardSubscribers = new Set();
    this.logger.info('Analytics Dashboard Subsystem initialized');
  }
 
  /**
   * Initialize the analytics dashboard subsystem
   */
  async init() {
    try {
      // Set up EventBus listeners for analytics collection
      this.setupEventBusListeners();
 
      // Initialize metrics collection
      await this.initializeMetricsCollection();
 
      // Set up periodic data collection
      this.startDataCollection();
 
      // Initialize alert system
      this.initializeAlertSystem();
      this.logger.info('Analytics Dashboard Subsystem initialized successfully');
      this.eventBus.emit('subsystem:ready', {
        subsystem: 'analytics-dashboard'
      });
    } catch (error) {
      this.logger.error('Failed to initialize Analytics Dashboard Subsystem', error);
      this.eventBus.emit('subsystem:error', {
        subsystem: 'analytics-dashboard',
        error
      });
      throw error;
    }
  }
 
  /**
   * Set up EventBus listeners for analytics collection
   */
  setupEventBusListeners() {
    this.logger.debug('Setting up EventBus listeners for analytics collection');
 
    // Operation events
    this.eventBus.on('operation:started', data => this.recordOperationStart(data));
    this.eventBus.on('operation:completed', data => this.recordOperationComplete(data));
    this.eventBus.on('operation:failed', data => this.recordOperationFailure(data));
    this.eventBus.on('operation:progress', data => this.recordOperationProgress(data));
 
    // System events
    this.eventBus.on('app:global-error', data => this.recordSystemError(data));
    this.eventBus.on('app:page-loaded', data => this.recordSystemPerformance(data));
    this.eventBus.on('subsystem:error', data => this.recordSubsystemError(data));
 
    // User activity events
    this.eventBus.on('session:user-joined', data => this.recordUserActivity(data));
    this.eventBus.on('session:user-left', data => this.recordUserActivity(data));
    this.eventBus.on('collaboration:user-joined', data => this.recordCollaborationActivity(data));
    this.eventBus.on('collaboration:user-left', data => this.recordCollaborationActivity(data));
 
    // Real-time events
    this.eventBus.on('progress-stream:update', data => this.recordRealtimeActivity(data));
    this.eventBus.on('notification:sent', data => this.recordRealtimeActivity(data));
    this.logger.debug('EventBus listeners set up for analytics collection');
  }
 
  /**
   * Initialize metrics collection
   */
  async initializeMetricsCollection() {
    this.logger.debug('Initializing metrics collection');
 
    // Initialize baseline metrics
    await this.collectSystemMetrics();
    await this.collectOperationMetrics();
    await this.collectUserMetrics();
    await this.collectRealtimeMetrics();
    this.logger.debug('Metrics collection initialized');
  }
 
  /**
   * Collect system metrics
   */
  async collectSystemMetrics() {
    try {
      const systemMetrics = this.getSystemPerformanceMetrics();
      this.addMetric('system.performance', systemMetrics);
      const resourceMetrics = this.getResourceUsageMetrics();
      this.addMetric('system.resources', resourceMetrics);
      const connectionMetrics = this.getConnectionMetrics();
      this.addMetric('system.connections', connectionMetrics);
      this.logger.debug('System metrics collected');
    } catch (error) {
      this.logger.error('Failed to collect system metrics', error);
    }
  }
 
  /**
   * Collect operation metrics
   */
  async collectOperationMetrics() {
    try {
      // Get operation counts and performance from other subsystems
      const operationData = {
        timestamp: new Date(),
        totalOperations: this.metrics.operations.imports.length + this.metrics.operations.exports.length + this.metrics.operations.modifications.length + this.metrics.operations.deletions.length,
        successfulOperations: this.getSuccessfulOperationsCount(),
        failedOperations: this.getFailedOperationsCount(),
        averageResponseTime: this.getAverageResponseTime()
      };
      this.addMetric('operations.summary', operationData);
      this.logger.debug('Operation metrics collected');
    } catch (error) {
      this.logger.error('Failed to collect operation metrics', error);
    }
  }
 
  /**
   * Collect user metrics
   */
  async collectUserMetrics() {
    try {
      const userMetrics = {
        timestamp: new Date(),
        activeSessions: this.sessionSubsystem ? await this.sessionSubsystem.getActiveSessionCount() : 0,
        totalUsers: this.metrics.users.sessions.length,
        collaborativeUsers: this.metrics.users.collaboration.length,
        averageSessionDuration: this.getAverageSessionDuration()
      };
      this.addMetric('users.activity', userMetrics);
      this.logger.debug('User metrics collected');
    } catch (error) {
      this.logger.error('Failed to collect user metrics', error);
    }
  }
 
  /**
   * Collect realtime metrics
   */
  async collectRealtimeMetrics() {
    try {
      const realtimeMetrics = this.getRealtimeMetrics();
      this.addMetric('realtime.performance', realtimeMetrics);
      this.logger.debug('Realtime metrics collected');
    } catch (error) {
      this.logger.error('Failed to collect realtime metrics', error);
    }
  }
 
  /**
   * Helper methods for metrics calculation
   */
  getSuccessfulOperationsCount() {
    let count = 0;
    Object.keys(this.metrics.operations).forEach(type => {
      count += this.metrics.operations[type].filter(op => op.status === 'success').length;
    });
    return count;
  }
  getFailedOperationsCount() {
    let count = 0;
    Object.keys(this.metrics.operations).forEach(type => {
      count += this.metrics.operations[type].filter(op => op.status === 'failed').length;
    });
    return count;
  }
  getAverageResponseTime() {
    let totalTime = 0;
    let count = 0;
    Object.keys(this.metrics.operations).forEach(type => {
      this.metrics.operations[type].forEach(op => {
        if (op.responseTime) {
          totalTime += op.responseTime;
          count++;
        }
      });
    });
    return count > 0 ? totalTime / count : 0;
  }
  getAverageSessionDuration() {
    if (this.metrics.users.sessions.length === 0) return 0;
    let totalDuration = 0;
    let count = 0;
    this.metrics.users.sessions.forEach(session => {
      if (session.duration) {
        totalDuration += session.duration;
        count++;
      }
    });
    return count > 0 ? totalDuration / count : 0;
  }
  getRecentAverageLatency() {
    const recentMetrics = this.metrics.realtime.latency.slice(-10); // Last 10 measurements
    if (recentMetrics.length === 0) return null;
    const totalLatency = recentMetrics.reduce((sum, metric) => sum + metric.value, 0);
    return totalLatency / recentMetrics.length;
  }
  getRecentErrorRate() {
    const now = new Date();
    const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
    const recentErrors = this.metrics.system.errors.filter(error => new Date(error.timestamp) > oneHourAgo);
    const recentOperations = [];
    Object.keys(this.metrics.operations).forEach(type => {
      recentOperations.push(...this.metrics.operations[type].filter(op => new Date(op.timestamp) > oneHourAgo));
    });
    if (recentOperations.length === 0) return 0;
    return recentErrors.length / recentOperations.length;
  }
 
  /**
   * Start periodic data collection
   */
  startDataCollection() {
    if (this.isCollecting) return;
    this.isCollecting = true;
    this.collectionInterval = setInterval(async () => {
      try {
        await this.collectPeriodicMetrics();
        this.cleanupOldData();
        this.checkAlertThresholds();
        this.notifyDashboardSubscribers();
      } catch (error) {
        this.logger.error('Error during periodic data collection', error);
      }
    }, this.config.samplingInterval);
    this.logger.info('Started periodic data collection', {
      interval: this.config.samplingInterval
    });
  }
 
  /**
   * Stop data collection
   */
  stopDataCollection() {
    if (!this.isCollecting) return;
    this.isCollecting = false;
    if (this.collectionInterval) {
      clearInterval(this.collectionInterval);
      this.collectionInterval = null;
    }
    this.logger.info('Stopped periodic data collection');
  }
 
  /**
   * Collect periodic metrics
   */
  async collectPeriodicMetrics() {
    const timestamp = new Date();
    try {
      // System performance metrics
      const systemMetrics = await this.getSystemPerformanceMetrics();
      this.addMetric('system.performance', {
        timestamp,
        ...systemMetrics
      });
    } catch (error) {
      this.logger.debug('Failed to collect system performance metrics', error);
    }
    try {
      // Resource usage metrics
      const resourceMetrics = await this.getResourceUsageMetrics();
      this.addMetric('system.resources', {
        timestamp,
        ...resourceMetrics
      });
    } catch (error) {
      this.logger.debug('Failed to collect resource usage metrics', error);
    }
    try {
      // Connection metrics
      const connectionMetrics = await this.getConnectionMetrics();
      this.addMetric('system.connections', {
        timestamp,
        ...connectionMetrics
      });
    } catch (error) {
      this.logger.debug('Failed to collect connection metrics', error);
    }
    try {
      // Real-time metrics
      const realtimeMetrics = await this.getRealtimeMetrics();
      this.addMetric('realtime.connections', {
        timestamp,
        ...realtimeMetrics
      });
    } catch (error) {
      this.logger.debug('Failed to collect realtime metrics', error);
    }
  }
 
  /**
   * Get comprehensive system performance metrics
   */
  async getSystemPerformanceMetrics() {
    const now = Date.now();
    const metrics = {
      timestamp: new Date(),
      // Memory metrics (if available)
      memory: this.getMemoryMetrics(),
      // Performance timing metrics
      timing: this.getPerformanceTimingMetrics(),
      // CPU usage estimation
      cpu: this.getCPUUsageEstimate(),
      // Session and time metrics
      session: {
        uptime: now - this.sessionStart,
        sessionDuration: this.formatDuration(now - this.sessionStart),
        lastActivity: now - this.lastActivity,
        currentTime: new Date().toLocaleString(),
        timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
      },
      // Browser and system info
      browser: {
        userAgent: navigator.userAgent,
        language: navigator.language,
        platform: navigator.platform,
        cookieEnabled: navigator.cookieEnabled,
        onLine: navigator.onLine,
        hardwareConcurrency: navigator.hardwareConcurrency || 'Unknown'
      },
      // Screen and viewport metrics
      display: {
        screenWidth: screen.width,
        screenHeight: screen.height,
        viewportWidth: window.innerWidth,
        viewportHeight: window.innerHeight,
        colorDepth: screen.colorDepth,
        pixelRatio: window.devicePixelRatio || 1
      },
      // Network connection info (if available)
      connection: this.getConnectionInfo(),
      // Performance metrics
      performance: {
        loadTime: this.getPageLoadTime(),
        domContentLoaded: this.getDOMContentLoadedTime(),
        resourcesLoaded: performance.getEntriesByType('resource').length,
        navigationTiming: this.getNavigationTiming()
      }
    };
    return metrics;
  }
 
  /**
   * Get memory metrics (if available)
   */
  getMemoryMetrics() {
    if (performance.memory) {
      const memory = performance.memory;
      return {
        used: memory.usedJSHeapSize,
        total: memory.totalJSHeapSize,
        limit: memory.jsHeapSizeLimit,
        usagePercentage: Math.round(memory.usedJSHeapSize / memory.jsHeapSizeLimit * 100),
        formattedUsed: this.formatBytes(memory.usedJSHeapSize),
        formattedTotal: this.formatBytes(memory.totalJSHeapSize),
        formattedLimit: this.formatBytes(memory.jsHeapSizeLimit)
      };
    }
    return null;
  }
 
  /**
   * Get performance timing metrics
   */
  getPerformanceTimingMetrics() {
    if (performance.timing) {
      const timing = performance.timing;
      return {
        navigationStart: timing.navigationStart,
        domContentLoaded: timing.domContentLoadedEventEnd - timing.navigationStart,
        loadComplete: timing.loadEventEnd - timing.navigationStart,
        domInteractive: timing.domInteractive - timing.navigationStart,
        firstPaint: this.getFirstPaintTime()
      };
    }
    return null;
  }
 
  /**
   * Estimate CPU usage based on performance metrics
   */
  getCPUUsageEstimate() {
    try {
      const startTime = performance.now();
      // Simple CPU-intensive operation for estimation
      let iterations = 0;
      const testDuration = 10; // 10ms test
      const endTime = startTime + testDuration;
      while (performance.now() < endTime) {
        iterations++;
      }
 
      // Normalize based on expected performance
      const expectedIterations = 100000; // Baseline for comparison
      const cpuScore = Math.min(100, Math.round(iterations / expectedIterations * 100));
      return {
        estimatedUsage: Math.max(0, 100 - cpuScore),
        performanceScore: cpuScore,
        iterations: iterations,
        testDuration: testDuration
      };
    } catch (error) {
      return {
        estimatedUsage: 'Unknown',
        error: error.message
      };
    }
  }
 
  /**
   * Get connection information
   */
  getConnectionInfo() {
    if (navigator.connection || navigator.mozConnection || navigator.webkitConnection) {
      const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
      return {
        effectiveType: connection.effectiveType || 'Unknown',
        downlink: connection.downlink || 'Unknown',
        rtt: connection.rtt || 'Unknown',
        saveData: connection.saveData || false
      };
    }
    return {
      status: 'Connection API not available'
    };
  }
 
  /**
   * Get page load time
   */
  getPageLoadTime() {
    if (performance.timing) {
      return performance.timing.loadEventEnd - performance.timing.navigationStart;
    }
    return null;
  }
 
  /**
   * Get DOM content loaded time
   */
  getDOMContentLoadedTime() {
    if (performance.timing) {
      return performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart;
    }
    return null;
  }
 
  /**
   * Get first paint time
   */
  getFirstPaintTime() {
    try {
      const paintEntries = performance.getEntriesByType('paint');
      const firstPaint = paintEntries.find(entry => entry.name === 'first-paint');
      return firstPaint ? firstPaint.startTime : null;
    } catch (error) {
      return null;
    }
  }
 
  /**
   * Get navigation timing
   */
  getNavigationTiming() {
    if (performance.getEntriesByType) {
      const navEntries = performance.getEntriesByType('navigation');
      if (navEntries.length > 0) {
        const nav = navEntries[0];
        return {
          type: nav.type,
          redirectCount: nav.redirectCount,
          transferSize: nav.transferSize,
          encodedBodySize: nav.encodedBodySize,
          decodedBodySize: nav.decodedBodySize
        };
      }
    }
    return null;
  }
 
  /**
   * Format bytes to human readable format
   */
  formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
 
  /**
   * Format duration to human readable format
   */
  formatDuration(milliseconds) {
    const seconds = Math.floor(milliseconds / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    if (days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m`;
    if (hours > 0) return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
    if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
    return `${seconds}s`;
  }
 
  /**
   * Record user activity
   */
  recordActivity(type) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.lastActivity = Date.now();
    const activity = {
      timestamp: new Date(),
      type: type,
      data: data
    };
    this.activityHistory.push(activity);
 
    // Keep only recent activities (last 100)
    if (this.activityHistory.length > 100) {
      this.activityHistory = this.activityHistory.slice(-100);
    }
    this.addMetric('users.activity', activity);
  }
 
  /**
   * Get recent activity for dashboard
   */
  getRecentActivity() {
    let limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
    return this.activityHistory.slice(-limit).reverse();
  }
 
  /**
   * Get comprehensive dashboard data
   */
  async getDashboardData() {
    const systemMetrics = await this.getSystemPerformanceMetrics();
    const recentActivity = this.getRecentActivity(15);
    return {
      timestamp: new Date(),
      system: systemMetrics,
      activity: recentActivity,
      summary: {
        totalOperations: this.getTotalOperationsCount(),
        successfulOperations: this.getSuccessfulOperationsCount(),
        failedOperations: this.getFailedOperationsCount(),
        averageResponseTime: this.getAverageResponseTime(),
        errorRate: this.getErrorRate(),
        activeSubsystems: this.getActiveSubsystemCount(),
        uptime: this.formatDuration(Date.now() - this.sessionStart)
      },
      alerts: this.alerts || []
    };
  }
 
  /**
   * Get total operations count
   */
  getTotalOperationsCount() {
    let count = 0;
    Object.keys(this.metrics.operations).forEach(type => {
      count += this.metrics.operations[type].length;
    });
    return count;
  }
 
  /**
   * Get resource usage metrics
   */
  async getResourceUsageMetrics() {
    try {
      return {
        timestamp: new Date(),
        // DOM elements count
        domElements: document.querySelectorAll('*').length,
        // Storage usage
        localStorage: this.getLocalStorageUsage(),
        sessionStorage: this.getSessionStorageUsage(),
        // Event listeners count (estimated)
        eventListeners: this.getEventListenerCount(),
        // Active timers and intervals (estimated)
        activeTimers: this.getActiveTimerCount(),
        // Resource entries from Performance API
        resourceEntries: performance.getEntriesByType('resource').length,
        // Network resources
        networkResources: this.getNetworkResourceCount(),
        // Memory metrics (if available)
        memoryUsage: this.getMemoryMetrics(),
        // Total metrics stored
        totalMetrics: this.getTotalMetricsCount()
      };
    } catch (error) {
      this.logger.debug('Failed to collect resource usage metrics', error);
      return {
        timestamp: new Date(),
        error: error.message
      };
    }
  }
 
  /**
   * Get connection metrics
   */
  async getConnectionMetrics() {
    const connectionStatus = this.advancedRealtime?.realtimeCommunication?.getConnectionStatus() || {};
    return {
      timestamp: new Date(),
      isConnected: connectionStatus.isConnected || false,
      connectionType: connectionStatus.connectionType || 'none',
      reconnectAttempts: connectionStatus.reconnectAttempts || 0,
      activeUsers: this.advancedRealtime?.activeUsers?.size || 0,
      collaborationRooms: this.advancedRealtime?.collaborationRooms?.size || 0
    };
  }
 
  /**
   * Get real-time metrics
   */
  async getRealtimeMetrics() {
    return {
      timestamp: new Date(),
      liveProgressStreams: this.advancedRealtime?.liveProgressStreams?.size || 0,
      notificationQueues: this.advancedRealtime?.notificationQueues?.size || 0,
      analyticsStreams: this.advancedRealtime?.analyticsStreams?.size || 0,
      messagesSent: this.getRealtimeMessageCount(),
      messagesReceived: this.getRealtimeMessageCount('received')
    };
  }
 
  /**
   * Record operation start
   */
  recordOperationStart(data) {
    this.addMetric(`operations.${data.type || 'unknown'}`, {
      timestamp: new Date(),
      event: 'started',
      operationId: data.operationId,
      type: data.type,
      userId: data.userId,
      metadata: data.metadata || {}
    });
    this.logger.debug('Recorded operation start', {
      type: data.type,
      operationId: data.operationId
    });
  }
 
  /**
   * Record operation completion
   */
  recordOperationComplete(data) {
    this.addMetric(`operations.${data.type || 'unknown'}`, {
      timestamp: new Date(),
      event: 'completed',
      operationId: data.operationId,
      type: data.type,
      duration: data.duration,
      recordsProcessed: data.recordsProcessed,
      success: true,
      metadata: data.metadata || {}
    });
    this.logger.debug('Recorded operation completion', {
      type: data.type,
      operationId: data.operationId
    });
  }
 
  /**
   * Record operation failure
   */
  recordOperationFailure(data) {
    this.addMetric(`operations.${data.type || 'unknown'}`, {
      timestamp: new Date(),
      event: 'failed',
      operationId: data.operationId,
      type: data.type,
      error: data.error,
      duration: data.duration,
      success: false,
      metadata: data.metadata || {}
    });
    this.logger.debug('Recorded operation failure', {
      type: data.type,
      operationId: data.operationId
    });
  }
 
  /**
   * Record system error
   */
  recordSystemError(data) {
    const errorMetric = {
      timestamp: new Date(),
      type: 'system-error',
      error: data.error || data.message || 'Unknown error',
      stack: data.stack,
      context: data.context || {},
      severity: data.severity || 'error'
    };
    this.addMetric('system.errors', errorMetric);
    this.logger.debug('System error recorded', errorMetric);
  }
 
  /**
   * Record subsystem error
   */
  recordSubsystemError(data) {
    const errorMetric = {
      timestamp: new Date(),
      type: 'subsystem-error',
      subsystem: data.subsystem || 'unknown',
      error: data.error?.message || data.error || 'Unknown subsystem error',
      stack: data.error?.stack,
      context: data.context || {},
      severity: 'error'
    };
    this.addMetric('system.errors', errorMetric);
    this.logger.debug('Subsystem error recorded', errorMetric);
  }
 
  /**
   * Record user activity
   */
  recordUserActivity(data) {
    this.addMetric('users.activity', {
      timestamp: new Date(),
      event: data.event || 'activity',
      userId: data.userId,
      sessionId: data.sessionId,
      metadata: data.metadata || {}
    });
    this.logger.debug('Recorded user activity', {
      event: data.event,
      userId: data.userId
    });
  }
 
  /**
   * Record collaboration activity
   */
  recordCollaborationActivity(data) {
    this.addMetric('users.collaboration', {
      timestamp: new Date(),
      event: data.event || 'collaboration',
      userId: data.userId || data.user?.id,
      roomId: data.roomId,
      userCount: data.totalUsers,
      metadata: data.metadata || {}
    });
    this.logger.debug('Recorded collaboration activity', {
      event: data.event,
      roomId: data.roomId
    });
  }
 
  /**
   * Record real-time activity
   */
  recordRealtimeActivity(data) {
    this.addMetric('realtime.messages', {
      timestamp: new Date(),
      type: data.type || 'message',
      operationId: data.operationId,
      recipients: data.recipients?.length || 0,
      metadata: data.metadata || {}
    });
    this.logger.debug('Recorded real-time activity', {
      type: data.type
    });
  }
 
  /**
   * Get analytics dashboard data
   */
  async getAnalyticsDashboardData() {
    let timeRange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '1h';
    const endTime = new Date();
    const startTime = new Date(endTime.getTime() - this.parseTimeRange(timeRange));
    try {
      const dashboardData = {
        timestamp: endTime,
        timeRange,
        summary: await this.getSummaryMetrics(startTime, endTime),
        systemMetrics: await this.getSystemMetricsData(startTime, endTime),
        operationMetrics: await this.getOperationMetricsData(startTime, endTime),
        userMetrics: await this.getUserMetricsData(startTime, endTime),
        realtimeMetrics: await this.getRealtimeMetricsData(startTime, endTime),
        alerts: this.getActiveAlerts(),
        trends: await this.getTrendAnalysis(startTime, endTime)
      };
      return dashboardData;
    } catch (error) {
      this.logger.error('Failed to get analytics dashboard data', error);
      throw error;
    }
  }
 
  /**
   * Get summary metrics
   */
  async getSummaryMetrics(startTime, endTime) {
    return {
      totalOperations: this.countMetricsInRange('operations', startTime, endTime),
      successfulOperations: this.countSuccessfulOperations(startTime, endTime),
      failedOperations: this.countFailedOperations(startTime, endTime),
      activeUsers: this.advancedRealtime?.activeUsers?.size || 0,
      systemErrors: this.countMetricsInRange('system.errors', startTime, endTime),
      averageLatency: this.getAverageLatency(startTime, endTime),
      memoryUsage: this.getCurrentMemoryUsage(),
      connectionStatus: this.advancedRealtime?.realtimeCommunication?.getConnectionStatus()
    };
  }
 
  /**
   * Get system metrics data for charts
   */
  async getSystemMetricsData(startTime, endTime) {
    const performanceData = this.getMetricsInRange('system.performance', startTime, endTime);
    const resourceData = this.getMetricsInRange('system.resources', startTime, endTime);
    const connectionData = this.getMetricsInRange('system.connections', startTime, endTime);
    return {
      performance: this.formatTimeSeriesData(performanceData, 'memory.usage'),
      resources: this.formatTimeSeriesData(resourceData, 'domElements'),
      connections: this.formatTimeSeriesData(connectionData, 'activeUsers'),
      errors: this.getMetricsInRange('system.errors', startTime, endTime)
    };
  }
 
  /**
   * Get operation metrics data for charts
   */
  async getOperationMetricsData(startTime, endTime) {
    const imports = this.getMetricsInRange('operations.imports', startTime, endTime);
    const exports = this.getMetricsInRange('operations.exports', startTime, endTime);
    const modifications = this.getMetricsInRange('operations.modifications', startTime, endTime);
    const deletions = this.getMetricsInRange('operations.deletions', startTime, endTime);
    return {
      imports: this.aggregateOperationMetrics(imports),
      exports: this.aggregateOperationMetrics(exports),
      modifications: this.aggregateOperationMetrics(modifications),
      deletions: this.aggregateOperationMetrics(deletions),
      timeline: this.createOperationTimeline(startTime, endTime)
    };
  }
 
  /**
   * Subscribe to dashboard updates
   */
  subscribeToDashboardUpdates(callback) {
    this.dashboardSubscribers.add(callback);
    return () => this.dashboardSubscribers.delete(callback);
  }
 
  /**
   * Notify dashboard subscribers
   */
  notifyDashboardSubscribers() {
    if (this.dashboardSubscribers.size > 0) {
      this.getAnalyticsDashboardData().then(data => {
        this.dashboardSubscribers.forEach(callback => {
          try {
            callback(data);
          } catch (error) {
            this.logger.error('Error notifying dashboard subscriber', error);
          }
        });
      });
    }
  }
 
  // Utility Methods
 
  addMetric(category, data) {
    const [main, sub] = category.split('.');
    if (!this.metrics[main]) this.metrics[main] = {};
    if (!this.metrics[main][sub]) this.metrics[main][sub] = [];
    this.metrics[main][sub].push(data);
 
    // Maintain max data points
    if (this.metrics[main][sub].length > this.config.maxDataPoints) {
      this.metrics[main][sub].shift();
    }
  }
  getMetricsInRange(category, startTime, endTime) {
    const [main, sub] = category.split('.');
    const metrics = this.metrics[main]?.[sub] || [];
    return metrics.filter(metric => metric.timestamp >= startTime && metric.timestamp <= endTime);
  }
  countMetricsInRange(category, startTime, endTime) {
    return this.getMetricsInRange(category, startTime, endTime).length;
  }
  parseTimeRange(timeRange) {
    const units = {
      'm': 60 * 1000,
      'h': 60 * 60 * 1000,
      'd': 24 * 60 * 60 * 1000
    };
    const match = timeRange.match(/^(\d+)([mhd])$/);
    if (!match) return 60 * 60 * 1000; // Default 1 hour
 
    const [, value, unit] = match;
    return parseInt(value) * units[unit];
  }
  cleanupOldData() {
    const cutoffTime = new Date(Date.now() - this.config.metricsRetention);
    Object.keys(this.metrics).forEach(main => {
      Object.keys(this.metrics[main]).forEach(sub => {
        this.metrics[main][sub] = this.metrics[main][sub].filter(metric => metric.timestamp > cutoffTime);
      });
    });
  }
  async measureConnectionLatency() {
    try {
      if (!this.advancedRealtime?.realtimeCommunication?.isConnected) {
        return null;
      }
      if (!this.advancedRealtime.realtimeCommunication.socket) {
        return null;
      }
      const start = performance.now();
      return new Promise(resolve => {
        try {
          this.advancedRealtime.realtimeCommunication.socket.emit('ping', start, () => {
            const latency = performance.now() - start;
            resolve(latency);
          });
 
          // Timeout after 3 seconds to prevent hanging
          setTimeout(() => resolve(null), 3000);
        } catch (error) {
          this.logger.debug('Error emitting ping for latency measurement', error);
          resolve(null);
        }
      });
    } catch (error) {
      this.logger.debug('Error measuring connection latency', error);
      return null;
    }
  }
  getActiveSubsystemCount() {
    // This would typically come from the main app
    return Object.keys(window.app?.subsystems || {}).length;
  }
  getEventListenerCount() {
    // EventBus doesn't have listenerCount method, return estimated count
    try {
      if (this.eventBus && this.eventBus._events) {
        return Object.keys(this.eventBus._events).length;
      }
      return 0;
    } catch (error) {
      return 0;
    }
  }
  getRealtimeMessageCount() {
    let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'sent';
    // Return message count from advanced realtime subsystem if available
    try {
      if (this.advancedRealtime && this.advancedRealtime.getMessageCount) {
        return this.advancedRealtime.getMessageCount(type);
      }
      // Fallback to estimated count
      return this.advancedRealtime?.messageCount || 0;
    } catch (error) {
      return 0;
    }
  }
  getLocalStorageUsage() {
    try {
      let total = 0;
      for (let key in localStorage) {
        if (localStorage.hasOwnProperty(key)) {
          total += localStorage[key].length + key.length;
        }
      }
      return total;
    } catch (error) {
      return 0;
    }
  }
  getSessionStorageUsage() {
    try {
      let total = 0;
      for (let key in sessionStorage) {
        if (sessionStorage.hasOwnProperty(key)) {
          total += sessionStorage[key].length + key.length;
        }
      }
      return total;
    } catch (error) {
      return 0;
    }
  }
 
  /**
   * Get local storage usage
   */
  getLocalStorageUsage() {
    try {
      let total = 0;
      for (let key in localStorage) {
        if (localStorage.hasOwnProperty(key)) {
          total += localStorage[key].length + key.length;
        }
      }
      return total;
    } catch (error) {
      return 0;
    }
  }
 
  /**
   * Get active timer count (estimated)
   */
  getActiveTimerCount() {
    // This is an estimation as there's no direct way to count active timers
    // We can track our own timers and make educated guesses
    let count = 0;
 
    // Count our own timers
    if (this.collectionInterval) count++;
    if (this.alertCheckInterval) count++;
 
    // Estimate based on common patterns
    // Most web apps have 5-20 active timers
    return count + 5; // Base estimate
  }
 
  /**
   * Get network resource count
   */
  getNetworkResourceCount() {
    try {
      const resources = performance.getEntriesByType('resource');
      return {
        total: resources.length,
        scripts: resources.filter(r => r.name.includes('.js')).length,
        stylesheets: resources.filter(r => r.name.includes('.css')).length,
        images: resources.filter(r => /\.(png|jpg|jpeg|gif|svg|webp)/.test(r.name)).length,
        xhr: resources.filter(r => r.initiatorType === 'xmlhttprequest').length,
        fetch: resources.filter(r => r.initiatorType === 'fetch').length
      };
    } catch (error) {
      return {
        total: 0,
        error: error.message
      };
    }
  }
 
  /**
   * Initialize alert system
   */
  initializeAlertSystem() {
    this.alerts = [];
    this.logger.debug('Alert system initialized');
  }
 
  /**
   * Check alert thresholds
   */
  checkAlertThresholds() {
    if (!this.alertsEnabled) return;
 
    // Memory usage alert
    if (performance.memory) {
      const memoryUsage = performance.memory.usedJSHeapSize / performance.memory.totalJSHeapSize;
      if (memoryUsage > this.config.alertThresholds.memoryUsage) {
        this.createAlert('high-memory-usage', `Memory usage is ${(memoryUsage * 100).toFixed(1)}%`, 'warning');
      }
    }
 
    // Connection latency alert
    const recentLatency = this.getRecentAverageLatency();
    if (recentLatency && recentLatency > this.config.alertThresholds.connectionLatency) {
      this.createAlert('high-latency', `Connection latency is ${recentLatency.toFixed(0)}ms`, 'warning');
    }
 
    // Error rate alert
    const errorRate = this.getRecentErrorRate();
    if (errorRate > this.config.alertThresholds.errorRate) {
      this.createAlert('high-error-rate', `Error rate is ${(errorRate * 100).toFixed(1)}%`, 'error');
    }
  }
  createAlert(id, message, severity) {
    const alert = {
      id,
      message,
      severity,
      timestamp: new Date(),
      acknowledged: false
    };
 
    // Avoid duplicate alerts
    if (!this.alerts.find(a => a.id === id && !a.acknowledged)) {
      this.alerts.push(alert);
      this.eventBus.emit('analytics:alert-created', alert);
      this.logger.warn('Analytics alert created', alert);
    }
  }
  getActiveAlerts() {
    return this.alerts.filter(alert => !alert.acknowledged);
  }
 
  /**
   * Cleanup and disconnect
   */
  async disconnect() {
    this.logger.info('Disconnecting Analytics Dashboard Subsystem');
    this.stopDataCollection();
    this.dashboardSubscribers.clear();
 
    // Clear metrics data
    Object.keys(this.metrics).forEach(main => {
      Object.keys(this.metrics[main]).forEach(sub => {
        this.metrics[main][sub] = [];
      });
    });
    this.logger.info('Analytics Dashboard Subsystem disconnected');
  }
 
  /**
   * Get subsystem status
   */
  getStatus() {
    return {
      isInitialized: true,
      isCollecting: this.isCollecting,
      metricsCount: this.getTotalMetricsCount(),
      alertsCount: this.getActiveAlerts().length,
      subscribersCount: this.dashboardSubscribers.size,
      timestamp: new Date()
    };
  }
  getTotalMetricsCount() {
    let total = 0;
    Object.keys(this.metrics).forEach(main => {
      Object.keys(this.metrics[main]).forEach(sub => {
        total += this.metrics[main][sub].length;
      });
    });
    return total;
  }
}
exports.AnalyticsDashboardSubsystem = AnalyticsDashboardSubsystem;
 
},{}],85:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AuthManagementSubsystem = void 0;
/**
 * Authentication Management Subsystem
 * 
 * Handles all authentication-related operations including token management,
 * credential validation, and authentication state tracking.
 */
 
class AuthManagementSubsystem {
  constructor(logger, uiManager, localClient, settingsSubsystem) {
    this.logger = logger;
    this.uiManager = uiManager;
    this.localClient = localClient;
    this.settingsSubsystem = settingsSubsystem;
 
    // Authentication state
    this.isAuthenticated = false;
    this.tokenStatus = null;
    this.tokenExpiry = null;
    this.refreshTimer = null;
    this.logger.info('Authentication Management Subsystem initialized');
  }
 
  /**
   * Initialize the authentication subsystem
   */
  async init() {
    try {
      this.setupEventListeners();
      await this.checkInitialTokenStatus();
      this.setupTokenRefreshTimer();
      this.logger.info('Authentication Management Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Authentication Management Subsystem', error);
      throw error;
    }
  }
 
  /**
   * Set up event listeners for authentication-related elements
   */
  setupEventListeners() {
    // Get token button
    const getTokenBtn = document.getElementById('get-token-btn');
    if (getTokenBtn) {
      getTokenBtn.addEventListener('click', async e => {
        e.preventDefault();
        await this.getToken();
      });
    }
 
    // Test connection button
    const testConnectionBtn = document.getElementById('test-connection-btn');
    if (testConnectionBtn) {
      testConnectionBtn.addEventListener('click', async e => {
        e.preventDefault();
        await this.testConnection();
      });
    }
 
    // Global token refresh button
    const globalRefreshBtn = document.getElementById('global-refresh-token');
    if (globalRefreshBtn) {
      globalRefreshBtn.addEventListener('click', async e => {
        e.preventDefault();
        await this.refreshToken();
      });
    }
 
    // Settings form submission
    const settingsForm = document.getElementById('settings-form');
    if (settingsForm) {
      settingsForm.addEventListener('submit', async e => {
        e.preventDefault();
        await this.handleSettingsSubmit(e);
      });
    }
  }
 
  /**
   * Get a new authentication token
   */
  async getToken() {
    try {
      this.logger.info('Getting new authentication token');
      this.showTokenProgress('Getting token...');
 
      // Validate settings first
      await this.settingsSubsystem.loadCurrentSettings();
      const settings = this.settingsSubsystem.currentSettings;
      if (!this.validateSettings(settings)) {
        throw new Error('Invalid settings - please check your configuration');
      }
 
      // Request token from server
      const response = await this.localClient.post('/api/v1/auth/token', {
        clientId: settings.clientId,
        clientSecret: settings.clientSecret,
        environmentId: settings.environmentId,
        region: settings.region
      });
      if (!response.success) {
        throw new Error(response.error || 'Failed to get token');
      }
 
      // Update token status
      this.tokenStatus = response.token;
      this.tokenExpiry = response.expiry;
      this.isAuthenticated = true;
 
      // Update UI
      this.updateTokenStatusUI(true, 'Token obtained successfully');
      this.uiManager.showSuccess('Authentication successful');
 
      // Set up refresh timer
      this.setupTokenRefreshTimer();
      this.logger.info('Token obtained successfully');
    } catch (error) {
      this.logger.error('Failed to get token', error);
      this.updateTokenStatusUI(false, error.message);
      this.uiManager.showError('Authentication Failed', error.message);
    } finally {
      this.hideTokenProgress();
    }
  }
 
  /**
   * Test connection with current settings
   */
  async testConnection() {
    try {
      this.logger.info('Testing connection');
      this.showConnectionProgress('Testing connection...');
 
      // Get current settings
      await this.settingsSubsystem.loadCurrentSettings();
      const settings = this.settingsSubsystem.currentSettings;
      if (!this.validateSettings(settings)) {
        throw new Error('Invalid settings - please check your configuration');
      }
 
      // Test connection
      // CRITICAL: Use GET request to match server-side endpoint
      // Server endpoint: routes/pingone-proxy-fixed.js - router.get('/test-connection')
      // Last fixed: 2025-07-21 - HTTP method mismatch caused 400 Bad Request errors
      const response = await this.localClient.get('/api/pingone/test-connection');
      if (!response.success) {
        throw new Error(response.error || 'Connection test failed');
      }
 
      // Update UI
      this.updateConnectionStatusUI(true, 'Connection successful');
      this.uiManager.showSuccess('Connection test successful');
      this.logger.info('Connection test successful');
    } catch (error) {
      this.logger.error('Connection test failed', error);
      this.updateConnectionStatusUI(false, error.message);
      this.uiManager.showError('Connection Test Failed', error.message);
    } finally {
      this.hideConnectionProgress();
    }
  }
 
  /**
   * Refresh the current token
   */
  async refreshToken() {
    try {
      this.logger.info('Refreshing authentication token');
      this.showTokenProgress('Refreshing token...');
      const response = await this.localClient.post('/api/v1/auth/refresh');
      if (!response.success) {
        throw new Error(response.error || 'Failed to refresh token');
      }
 
      // Update token status
      this.tokenStatus = response.token;
      this.tokenExpiry = response.expiry;
      this.isAuthenticated = true;
 
      // Update UI
      this.updateTokenStatusUI(true, 'Token refreshed successfully');
      this.uiManager.showSuccess('Token refreshed successfully');
 
      // Reset refresh timer
      this.setupTokenRefreshTimer();
      this.logger.info('Token refreshed successfully');
    } catch (error) {
      this.logger.error('Failed to refresh token', error);
      this.updateTokenStatusUI(false, error.message);
      this.uiManager.showError('Token Refresh Failed', error.message);
 
      // Clear authentication state
      this.clearAuthenticationState();
    } finally {
      this.hideTokenProgress();
    }
  }
 
  /**
   * Handle settings form submission
   */
  async handleSettingsSubmit(event) {
    try {
      const formData = new FormData(event.target);
      const settings = Object.fromEntries(formData.entries());
      this.logger.info('Saving settings');
 
      // Validate settings
      if (!this.validateSettings(settings)) {
        throw new Error('Invalid settings - please check all required fields');
      }
 
      // Save settings
      await this.settingsManager.saveSettings(settings);
 
      // Clear current authentication state since settings changed
      this.clearAuthenticationState();
 
      // Update UI
      this.uiManager.updateSettingsSaveStatus('Settings saved successfully', 'success');
      this.logger.info('Settings saved successfully');
    } catch (error) {
      this.logger.error('Failed to save settings', error);
      this.uiManager.updateSettingsSaveStatus(`Settings Save Failed: ${error.message}`, 'error');
    }
  }
 
  /**
   * Check initial token status and automatically acquire new token if expired
   * CRITICAL: This method provides automatic token acquisition at startup
   * DO NOT REMOVE OR MODIFY without understanding the startup authentication flow
   */
  async checkInitialTokenStatus() {
    try {
      this.logger.debug('🔍 [STARTUP] Checking initial token status...');
      const response = await this.localClient.get('/api/v1/auth/status');
      if (response.success && response.isValid) {
        // Token is valid - set authentication state
        this.tokenStatus = response.status;
        this.tokenExpiry = response.expiresIn;
        this.isAuthenticated = true;
        this.updateTokenStatusUI(true, `Token is ${response.status}`);
        this.logger.info('✅ [STARTUP] Valid token found, authentication ready');
      } else if (response.success && response.hasToken) {
        // Token exists but is expired - attempt automatic refresh
        this.logger.warn('⚠️ [STARTUP] Token expired, attempting automatic refresh...');
        this.tokenStatus = response.status;
        this.tokenExpiry = response.expiresIn;
 
        // Attempt automatic token acquisition
        const refreshSuccess = await this.attemptAutomaticTokenRefresh();
        if (refreshSuccess) {
          this.logger.info('✅ [STARTUP] Token automatically refreshed, authentication ready');
        } else {
          this.logger.warn('❌ [STARTUP] Automatic token refresh failed, user intervention required');
          this.isAuthenticated = false;
          this.updateTokenStatusUI(false, 'Token expired - refresh required');
        }
      } else {
        // No token available - attempt automatic acquisition if credentials exist
        this.logger.warn('⚠️ [STARTUP] No token found, attempting automatic acquisition...');
        const acquisitionSuccess = await this.attemptAutomaticTokenRefresh();
        if (acquisitionSuccess) {
          this.logger.info('✅ [STARTUP] Token automatically acquired, authentication ready');
        } else {
          this.logger.warn('❌ [STARTUP] No token available and automatic acquisition failed');
          this.isAuthenticated = false;
          this.updateTokenStatusUI(false, response.status || 'No valid token');
        }
      }
    } catch (error) {
      this.logger.error('❌ [STARTUP] Failed to check token status', error);
      this.isAuthenticated = false;
      this.updateTokenStatusUI(false, 'Token status unknown');
    }
  }
 
  /**
   * Attempt automatic token refresh/acquisition at startup
   * CRITICAL: This method enables automatic token acquisition when credentials are available
   * DO NOT REMOVE - Required for seamless startup authentication flow
   */
  async attemptAutomaticTokenRefresh() {
    try {
      this.logger.debug('🔄 [STARTUP] Attempting automatic token acquisition...');
 
      // Load current settings to check if credentials are available
      await this.settingsSubsystem.loadCurrentSettings();
      const settings = this.settingsSubsystem.currentSettings;
 
      // Validate that we have the required credentials
      if (!this.validateSettings(settings)) {
        this.logger.debug('❌ [STARTUP] No valid credentials available for automatic token acquisition');
        return false;
      }
      this.logger.debug('✅ [STARTUP] Valid credentials found, attempting token acquisition...');
 
      // Request token from server using available credentials
      const response = await this.localClient.post('/api/v1/auth/token', {
        clientId: settings.clientId,
        clientSecret: settings.clientSecret,
        environmentId: settings.environmentId,
        region: settings.region
      });
      if (response.success && response.token) {
        // Token acquisition successful - update authentication state
        this.tokenStatus = response.token;
        this.tokenExpiry = response.expiry;
        this.isAuthenticated = true;
 
        // Update UI to reflect successful authentication
        this.updateTokenStatusUI(true, 'Token obtained automatically');
 
        // Set up refresh timer for the new token
        this.setupTokenRefreshTimer();
        this.logger.info('✅ [STARTUP] Automatic token acquisition successful');
        return true;
      } else {
        this.logger.warn('❌ [STARTUP] Token acquisition failed:', response.error || 'Unknown error');
        return false;
      }
    } catch (error) {
      this.logger.error('❌ [STARTUP] Error during automatic token acquisition:', error);
      return false;
    }
  }
 
  /**
   * Set up automatic token refresh timer
   * CRITICAL: This method manages token refresh scheduling
   * DO NOT REMOVE - Required for automatic token maintenance
   */
  setupTokenRefreshTimer() {
    // Clear existing timer
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
    }
    if (!this.tokenExpiry) {
      return;
    }
 
    // Calculate refresh time (5 minutes before expiry)
    const expiryTime = new Date(this.tokenExpiry).getTime();
    const refreshTime = expiryTime - 5 * 60 * 1000; // 5 minutes before
    const now = Date.now();
    if (refreshTime > now) {
      const delay = refreshTime - now;
      this.refreshTimer = setTimeout(() => {
        this.refreshToken();
      }, delay);
      this.logger.info('Token refresh timer set', {
        refreshIn: Math.round(delay / 1000 / 60),
        unit: 'minutes'
      });
    }
  }
 
  /**
   * Validate settings object
   */
  validateSettings(settings) {
    const required = ['clientId', 'clientSecret', 'environmentId', 'region'];
    for (const field of required) {
      if (!settings[field] || settings[field].trim() === '') {
        this.logger.error('Missing required setting', {
          field
        });
        return false;
      }
    }
    return true;
  }
 
  /**
   * Clear authentication state
   */
  clearAuthenticationState() {
    this.isAuthenticated = false;
    this.tokenStatus = null;
    this.tokenExpiry = null;
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
      this.refreshTimer = null;
    }
    this.updateTokenStatusUI(false, 'Authentication cleared');
  }
 
  /**
   * Update token status UI
   */
  updateTokenStatusUI(isValid, message) {
    // Update global token status
    const globalTokenStatus = document.getElementById('global-token-status');
    if (globalTokenStatus) {
      globalTokenStatus.className = `token-status ${isValid ? 'valid' : 'invalid'}`;
      globalTokenStatus.textContent = message;
    }
 
    // Update token indicator
    const tokenIndicator = document.getElementById('token-status-indicator');
    if (tokenIndicator) {
      tokenIndicator.className = `token-indicator ${isValid ? 'valid' : 'invalid'}`;
    }
 
    // Update get token button visibility
    const getTokenBtn = document.getElementById('get-token-btn');
    if (getTokenBtn) {
      getTokenBtn.style.display = isValid ? 'none' : 'inline-block';
    }
 
    // Update refresh token button visibility
    const refreshTokenBtn = document.getElementById('global-refresh-token');
    if (refreshTokenBtn) {
      refreshTokenBtn.style.display = isValid ? 'inline-block' : 'none';
    }
  }
 
  /**
   * Update connection status UI
   */
  updateConnectionStatusUI(isConnected, message) {
    const connectionStatus = document.getElementById('connection-status');
    if (connectionStatus) {
      connectionStatus.className = `connection-status ${isConnected ? 'connected' : 'disconnected'}`;
      connectionStatus.textContent = message;
    }
  }
 
  /**
   * Show token progress
   */
  showTokenProgress(message) {
    const getTokenBtn = document.getElementById('get-token-btn');
    if (getTokenBtn) {
      getTokenBtn.disabled = true;
      getTokenBtn.textContent = message;
    }
  }
 
  /**
   * Hide token progress
   */
  hideTokenProgress() {
    const getTokenBtn = document.getElementById('get-token-btn');
    if (getTokenBtn) {
      getTokenBtn.disabled = false;
      getTokenBtn.textContent = 'Get Token';
    }
  }
 
  /**
   * Show connection progress
   */
  showConnectionProgress(message) {
    const testConnectionBtn = document.getElementById('test-connection-btn');
    if (testConnectionBtn) {
      testConnectionBtn.disabled = true;
      testConnectionBtn.textContent = message;
    }
  }
 
  /**
   * Hide connection progress
   */
  hideConnectionProgress() {
    const testConnectionBtn = document.getElementById('test-connection-btn');
    if (testConnectionBtn) {
      testConnectionBtn.disabled = false;
      testConnectionBtn.textContent = 'Test Connection';
    }
  }
 
  /**
   * Get current authentication status
   */
  getAuthenticationStatus() {
    return {
      isAuthenticated: this.isAuthenticated,
      tokenStatus: this.tokenStatus,
      tokenExpiry: this.tokenExpiry,
      timeUntilExpiry: this.tokenExpiry ? Math.max(0, new Date(this.tokenExpiry).getTime() - Date.now()) : 0
    };
  }
 
  /**
   * Check if token is valid and not expired
   */
  isTokenValid() {
    if (!this.isAuthenticated || !this.tokenExpiry) {
      return false;
    }
    const now = Date.now();
    const expiry = new Date(this.tokenExpiry).getTime();
    return expiry > now;
  }
}
exports.AuthManagementSubsystem = AuthManagementSubsystem;
 
},{}],86:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ConnectionManagerSubsystem = void 0;
var _browserLoggingService = require("../utils/browser-logging-service.js");
/**
 * Connection Manager Subsystem
 * 
 * Manages all PingOne connection functionality including token acquisition,
 * validation, connection testing, and credential management.
 * 
 * Features:
 * - Token acquisition and validation
 * - Connection testing and health checks
 * - Credential validation and storage
 * - Connection status monitoring
 * - Automatic token refresh
 * - Connection retry logic
 */
 
class ConnectionManagerSubsystem {
  constructor(logger, uiManager, settingsManager, apiClient) {
    this.logger = logger || (0, _browserLoggingService.createLogger)({
      serviceName: 'connection-manager-subsystem',
      environment: 'development'
    });
    this.uiManager = uiManager;
    this.settingsManager = settingsManager;
    this.apiClient = apiClient;
 
    // Connection state
    this.connectionStatus = 'disconnected';
    this.lastConnectionTest = null;
    this.tokenInfo = {
      token: null,
      expiresAt: null,
      isValid: false
    };
 
    // Connection monitoring
    this.healthCheckInterval = null;
    this.tokenRefreshInterval = null;
    this.connectionRetryCount = 0;
    this.maxRetryAttempts = 3;
 
    // Event listeners
    this.eventListeners = new Map();
    this.logger.info('Connection Manager subsystem initialized');
  }
 
  /**
   * Initialize the connection manager subsystem
   */
  async init() {
    try {
      this.logger.info('Initializing connection manager subsystem...');
 
      // Load existing token if available
      await this.loadExistingToken();
 
      // Start connection monitoring
      this.startConnectionMonitoring();
 
      // Set up automatic token refresh
      this.setupTokenRefresh();
      this.logger.info('Connection Manager subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize connection manager subsystem', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Test connection to PingOne
   * @param {Object} credentials - Optional credentials to test
   * @returns {Promise<Object>} - Connection test result
   */
  async testConnection() {
    let credentials = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    try {
      this.logger.info('Testing PingOne connection...');
 
      // Update UI to show testing state
      if (this.uiManager) {
        this.uiManager.updateConnectionStatus('testing', 'Testing connection...');
      }
 
      // Use provided credentials or get from settings
      const testCredentials = credentials || (await this.getCredentials());
      if (!testCredentials) {
        throw new Error('No credentials available for connection test');
      }
 
      // Validate credentials format
      this.validateCredentials(testCredentials);
 
      // Test connection by getting a token
      const tokenResult = await this.acquireToken(testCredentials);
      if (tokenResult.success) {
        this.connectionStatus = 'connected';
        this.lastConnectionTest = {
          timestamp: Date.now(),
          success: true,
          credentials: {
            clientId: testCredentials.clientId,
            environmentId: testCredentials.environmentId,
            region: testCredentials.region
          }
        };
 
        // Update UI
        if (this.uiManager) {
          this.uiManager.updateConnectionStatus('success', 'Connection successful');
        }
        this.logger.info('Connection test successful');
 
        // Emit connection success event
        this.emit('connectionSuccess', this.lastConnectionTest);
        return {
          success: true,
          message: 'Connection successful',
          token: tokenResult.token,
          expiresIn: tokenResult.expiresIn
        };
      } else {
        throw new Error(tokenResult.error || 'Failed to acquire token');
      }
    } catch (error) {
      this.logger.error('Connection test failed', {
        error: error.message
      });
      this.connectionStatus = 'disconnected';
      this.lastConnectionTest = {
        timestamp: Date.now(),
        success: false,
        error: error.message
      };
 
      // Update UI
      if (this.uiManager) {
        this.uiManager.updateConnectionStatus('error', `Connection failed: ${error.message}`);
      }
 
      // Emit connection failure event
      this.emit('connectionFailure', {
        error: error.message
      });
      return {
        success: false,
        error: error.message
      };
    }
  }
 
  /**
   * Acquire a new token from PingOne
   * @param {Object} credentials - PingOne credentials
   * @returns {Promise<Object>} - Token acquisition result
   */
  async acquireToken() {
    let credentials = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    try {
      this.logger.info('Acquiring PingOne token...');
 
      // Use provided credentials or get from settings
      const tokenCredentials = credentials || (await this.getCredentials());
      if (!tokenCredentials) {
        throw new Error('No credentials available for token acquisition');
      }
 
      // Validate credentials
      this.validateCredentials(tokenCredentials);
 
      // Make token request
      const response = await this.apiClient.post('/api/auth/token', {
        clientId: tokenCredentials.clientId,
        clientSecret: tokenCredentials.clientSecret,
        environmentId: tokenCredentials.environmentId,
        region: tokenCredentials.region
      });
      if (response.success && response.token) {
        // Store token info
        this.tokenInfo = {
          token: response.token,
          expiresAt: Date.now() + response.expiresIn * 1000,
          isValid: true,
          acquiredAt: Date.now()
        };
 
        // Update connection status
        this.connectionStatus = 'connected';
 
        // Update UI
        if (this.uiManager) {
          this.uiManager.updateTokenStatus(true, 'Token acquired successfully');
        }
        this.logger.info('Token acquired successfully', {
          expiresIn: response.expiresIn
        });
 
        // Emit token acquired event
        this.emit('tokenAcquired', {
          token: response.token,
          expiresIn: response.expiresIn
        });
        return {
          success: true,
          token: response.token,
          expiresIn: response.expiresIn
        };
      } else {
        throw new Error(response.error || 'Failed to acquire token');
      }
    } catch (error) {
      this.logger.error('Token acquisition failed', {
        error: error.message
      });
 
      // Clear token info
      this.tokenInfo = {
        token: null,
        expiresAt: null,
        isValid: false
      };
 
      // Update connection status
      this.connectionStatus = 'disconnected';
 
      // Update UI
      if (this.uiManager) {
        this.uiManager.updateTokenStatus(false, `Token acquisition failed: ${error.message}`);
      }
 
      // Emit token acquisition failure event
      this.emit('tokenAcquisitionFailure', {
        error: error.message
      });
      return {
        success: false,
        error: error.message
      };
    }
  }
 
  /**
   * Validate current token
   * @returns {Promise<boolean>} - Whether token is valid
   */
  async validateToken() {
    try {
      if (!this.tokenInfo.token) {
        this.logger.debug('No token to validate');
        return false;
      }
 
      // Check if token is expired
      if (this.tokenInfo.expiresAt && Date.now() >= this.tokenInfo.expiresAt) {
        this.logger.info('Token has expired');
        this.tokenInfo.isValid = false;
        return false;
      }
 
      // Test token with a simple API call
      const response = await this.apiClient.get('/api/auth/validate', {
        headers: {
          'Authorization': `Bearer ${this.tokenInfo.token}`
        }
      });
      const isValid = response.success;
      this.tokenInfo.isValid = isValid;
      if (isValid) {
        this.logger.debug('Token validation successful');
        this.connectionStatus = 'connected';
      } else {
        this.logger.info('Token validation failed');
        this.connectionStatus = 'disconnected';
      }
      return isValid;
    } catch (error) {
      this.logger.error('Token validation error', {
        error: error.message
      });
      this.tokenInfo.isValid = false;
      this.connectionStatus = 'disconnected';
      return false;
    }
  }
 
  /**
   * Refresh current token
   * @returns {Promise<Object>} - Token refresh result
   */
  async refreshToken() {
    try {
      this.logger.info('Refreshing token...');
 
      // Get current credentials
      const credentials = await this.getCredentials();
      if (!credentials) {
        throw new Error('No credentials available for token refresh');
      }
 
      // Acquire new token
      const result = await this.acquireToken(credentials);
      if (result.success) {
        this.logger.info('Token refreshed successfully');
 
        // Emit token refreshed event
        this.emit('tokenRefreshed', {
          token: result.token,
          expiresIn: result.expiresIn
        });
      }
      return result;
    } catch (error) {
      this.logger.error('Token refresh failed', {
        error: error.message
      });
 
      // Emit token refresh failure event
      this.emit('tokenRefreshFailure', {
        error: error.message
      });
      return {
        success: false,
        error: error.message
      };
    }
  }
 
  /**
   * Get current credentials
   * @returns {Promise<Object|null>} - Current credentials
   */
  async getCredentials() {
    try {
      // Try to get from credentials manager first
      if (window.credentialsManager) {
        const credentials = window.credentialsManager.getCredentials();
        if (credentials && this.isValidCredentialSet(credentials)) {
          return credentials;
        }
      }
 
      // Fallback to settings manager
      if (this.settingsManager) {
        await this.settingsManager.loadCurrentSettings();
        const settings = this.settingsManager.currentSettings;
        if (settings && this.isValidCredentialSet(settings)) {
          return {
            clientId: settings.clientId,
            clientSecret: settings.clientSecret,
            environmentId: settings.environmentId,
            region: settings.region
          };
        }
      }
      return null;
    } catch (error) {
      this.logger.error('Failed to get credentials', {
        error: error.message
      });
      return null;
    }
  }
 
  /**
   * Validate credentials format
   * @param {Object} credentials - Credentials to validate
   */
  validateCredentials(credentials) {
    const required = ['clientId', 'clientSecret', 'environmentId'];
    const missing = required.filter(field => !credentials[field]);
    if (missing.length > 0) {
      throw new Error(`Missing required credentials: ${missing.join(', ')}`);
    }
 
    // Validate format
    if (!/^[a-f0-9-]{36}$/.test(credentials.clientId)) {
      throw new Error('Invalid client ID format');
    }
    if (!/^[a-f0-9-]{36}$/.test(credentials.environmentId)) {
      throw new Error('Invalid environment ID format');
    }
    if (credentials.clientSecret.length < 10) {
      throw new Error('Client secret appears to be invalid');
    }
  }
 
  /**
   * Check if credential set is valid
   * @param {Object} credentials - Credentials to check
   * @returns {boolean} - Whether credentials are valid
   */
  isValidCredentialSet(credentials) {
    try {
      this.validateCredentials(credentials);
      return true;
    } catch (error) {
      return false;
    }
  }
 
  /**
   * Load existing token from storage
   */
  async loadExistingToken() {
    try {
      // Try to load from token manager
      if (window.globalTokenManager && typeof window.globalTokenManager.getCachedToken === 'function') {
        const cachedToken = window.globalTokenManager.getCachedToken();
        if (cachedToken) {
          this.tokenInfo = {
            token: cachedToken.token,
            expiresAt: cachedToken.expiresAt,
            isValid: cachedToken.isValid,
            acquiredAt: cachedToken.acquiredAt
          };
 
          // Validate the loaded token
          const isValid = await this.validateToken();
          if (isValid) {
            this.connectionStatus = 'connected';
            this.logger.info('Existing token loaded and validated');
          } else {
            this.logger.info('Existing token loaded but invalid');
          }
        }
      }
    } catch (error) {
      this.logger.error('Failed to load existing token', {
        error: error.message
      });
    }
  }
 
  /**
   * Start connection monitoring
   */
  startConnectionMonitoring() {
    // Health check every 5 minutes
    this.healthCheckInterval = setInterval(async () => {
      if (this.connectionStatus === 'connected') {
        const isValid = await this.validateToken();
        if (!isValid) {
          this.logger.info('Connection lost during health check');
          this.emit('connectionLost');
        }
      }
    }, 5 * 60 * 1000);
    this.logger.debug('Connection monitoring started');
  }
 
  /**
   * Setup automatic token refresh
   */
  setupTokenRefresh() {
    // Check token expiry every minute
    this.tokenRefreshInterval = setInterval(async () => {
      if (this.tokenInfo.token && this.tokenInfo.expiresAt) {
        const timeUntilExpiry = this.tokenInfo.expiresAt - Date.now();
        const refreshThreshold = 5 * 60 * 1000; // 5 minutes
 
        if (timeUntilExpiry <= refreshThreshold && timeUntilExpiry > 0) {
          this.logger.info('Token expiring soon, attempting refresh...');
          await this.refreshToken();
        }
      }
    }, 60 * 1000);
    this.logger.debug('Automatic token refresh setup');
  }
 
  /**
   * Get connection status
   * @returns {string} - Current connection status
   */
  getConnectionStatus() {
    return this.connectionStatus;
  }
 
  /**
   * Get token info
   * @returns {Object} - Current token information
   */
  getTokenInfo() {
    return {
      hasToken: !!this.tokenInfo.token,
      isValid: this.tokenInfo.isValid,
      expiresAt: this.tokenInfo.expiresAt,
      timeUntilExpiry: this.tokenInfo.expiresAt ? this.tokenInfo.expiresAt - Date.now() : null
    };
  }
 
  /**
   * Get last connection test result
   * @returns {Object|null} - Last connection test result
   */
  getLastConnectionTest() {
    return this.lastConnectionTest;
  }
 
  /**
   * Check if currently connected
   * @returns {boolean} - Whether currently connected
   */
  isConnected() {
    return this.connectionStatus === 'connected' && this.tokenInfo.isValid;
  }
 
  /**
   * Check if token is valid and not expired
   * @returns {boolean} - Whether token is valid
   */
  hasValidToken() {
    return this.tokenInfo.isValid && this.tokenInfo.token && this.tokenInfo.expiresAt && Date.now() < this.tokenInfo.expiresAt;
  }
 
  /**
   * Disconnect and clear token
   */
  disconnect() {
    this.logger.info('Disconnecting...');
 
    // Clear token info
    this.tokenInfo = {
      token: null,
      expiresAt: null,
      isValid: false
    };
 
    // Update connection status
    this.connectionStatus = 'disconnected';
 
    // Update UI
    if (this.uiManager) {
      this.uiManager.updateConnectionStatus('disconnected', 'Disconnected');
      this.uiManager.updateTokenStatus(false, 'No token');
    }
 
    // Emit disconnected event
    this.emit('disconnected');
    this.logger.info('Disconnected successfully');
  }
 
  /**
   * Add event listener
   * @param {string} event - Event name
   * @param {Function} listener - Event listener function
   */
  on(event, listener) {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, []);
    }
    this.eventListeners.get(event).push(listener);
  }
 
  /**
   * Remove event listener
   * @param {string} event - Event name
   * @param {Function} listener - Event listener function
   */
  off(event, listener) {
    if (this.eventListeners.has(event)) {
      const listeners = this.eventListeners.get(event);
      const index = listeners.indexOf(listener);
      if (index > -1) {
        listeners.splice(index, 1);
      }
    }
  }
 
  /**
   * Emit event
   * @param {string} event - Event name
   * @param {*} data - Event data
   */
  emit(event) {
    let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    if (this.eventListeners.has(event)) {
      this.eventListeners.get(event).forEach(listener => {
        try {
          listener(data);
        } catch (error) {
          this.logger.error('Event listener error', {
            event,
            error: error.message
          });
        }
      });
    }
  }
 
  /**
   * Get connection statistics
   * @returns {Object} - Connection statistics
   */
  getConnectionStats() {
    return {
      status: this.connectionStatus,
      hasToken: !!this.tokenInfo.token,
      tokenValid: this.tokenInfo.isValid,
      tokenExpiresAt: this.tokenInfo.expiresAt,
      lastConnectionTest: this.lastConnectionTest,
      retryCount: this.connectionRetryCount
    };
  }
 
  /**
   * Clean up the connection manager subsystem
   */
  cleanup() {
    // Clear intervals
    if (this.healthCheckInterval) {
      clearInterval(this.healthCheckInterval);
      this.healthCheckInterval = null;
    }
    if (this.tokenRefreshInterval) {
      clearInterval(this.tokenRefreshInterval);
      this.tokenRefreshInterval = null;
    }
 
    // Clear event listeners
    this.eventListeners.clear();
 
    // Disconnect
    this.disconnect();
    this.logger.info('Connection Manager subsystem cleaned up');
  }
}
exports.ConnectionManagerSubsystem = ConnectionManagerSubsystem;
 
},{"../utils/browser-logging-service.js":97}],87:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.EnhancedProgressSubsystem = void 0;
var _browserLoggingService = require("../utils/browser-logging-service.js");
/**
 * Enhanced Progress Subsystem
 * 
 * Modern progress tracking subsystem that handles all types of operations
 * (import, export, delete, modify) with real-time updates and better UI
 */
 
class EnhancedProgressSubsystem {
  constructor(logger, uiManager, eventBus, realtimeComm) {
    this.logger = logger || (0, _browserLoggingService.createLogger)({
      serviceName: 'enhanced-progress-subsystem',
      enableServer: true
    });
    this.uiManager = uiManager;
    this.eventBus = eventBus;
    this.realtimeComm = realtimeComm;
 
    // Progress state
    this.currentOperation = null;
    this.isActive = false;
    this.startTime = null;
    this.stats = {
      processed: 0,
      successful: 0,
      failed: 0,
      skipped: 0,
      total: 0,
      errors: []
    };
 
    // UI elements
    this.progressContainer = null;
    this.progressElements = {};
 
    // Operation types
    this.OPERATION_TYPES = {
      IMPORT: 'import',
      EXPORT: 'export',
      DELETE: 'delete',
      MODIFY: 'modify'
    };
    this.logger.info('Enhanced Progress Subsystem initialized');
  }
 
  /**
   * Initialize the subsystem
   */
  async init() {
    try {
      this.logger.debug('Initializing Enhanced Progress Subsystem...');
 
      // Set up event listeners
      this.setupEventListeners();
 
      // Set up real-time listeners
      this.setupRealtimeListeners();
 
      // Initialize progress UI for each operation type
      this.initializeProgressUI();
      this.logger.info('Enhanced Progress Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Enhanced Progress Subsystem', {
        error: error.message,
        stack: error.stack
      });
      throw error;
    }
  }
 
  /**
   * Set up event listeners
   */
  setupEventListeners() {
    // Listen for operation events
    this.eventBus.on('operation:started', data => {
      this.startOperation(data.type, data.options);
    });
    this.eventBus.on('operation:progress', data => {
      this.updateProgress(data);
    });
    this.eventBus.on('operation:completed', data => {
      this.completeOperation(data);
    });
    this.eventBus.on('operation:error', data => {
      this.handleError(data);
    });
    this.eventBus.on('operation:cancelled', data => {
      this.cancelOperation(data);
    });
    this.logger.debug('Enhanced Progress event listeners set up');
  }
 
  /**
   * Set up real-time listeners
   */
  setupRealtimeListeners() {
    if (this.realtimeComm) {
      this.realtimeComm.on('progress', data => {
        this.updateProgress(data);
      });
      this.realtimeComm.on('operation-complete', data => {
        this.completeOperation(data);
      });
      this.realtimeComm.on('operation-error', data => {
        this.handleError(data);
      });
      this.logger.debug('Enhanced Progress real-time listeners set up');
    }
  }
 
  /**
   * Initialize progress UI for all operation types
   */
  initializeProgressUI() {
    // Find existing progress containers or create them
    Object.values(this.OPERATION_TYPES).forEach(operationType => {
      const containerId = `${operationType}-progress-container`;
      let container = document.getElementById(containerId);
      if (!container) {
        container = this.createProgressContainer(operationType);
      }
      this.progressElements[operationType] = {
        container: container,
        progressBar: container.querySelector('.progress-bar-fill'),
        percentage: container.querySelector('.progress-percentage'),
        statusMessage: container.querySelector('.status-message'),
        progressText: container.querySelector('.progress-text'),
        statusDetails: container.querySelector('.status-details'),
        stats: {
          total: container.querySelector('.stat-value.total'),
          processed: container.querySelector('.stat-value.processed'),
          success: container.querySelector('.stat-value.success'),
          failed: container.querySelector('.stat-value.failed'),
          skipped: container.querySelector('.stat-value.skipped')
        },
        timing: {
          elapsed: container.querySelector('.elapsed-value'),
          eta: container.querySelector('.eta-value')
        },
        cancelButton: container.querySelector('.cancel-import-btn, .cancel-export-btn, .cancel-delete-btn, .cancel-modify-btn')
      };
    });
    this.logger.debug('Enhanced Progress UI initialized for all operation types');
  }
 
  /**
   * Create progress container for an operation type
   */
  createProgressContainer(operationType) {
    const container = document.createElement('div');
    container.id = `${operationType}-progress-container`;
    container.className = 'progress-container enhanced-progress';
    container.style.display = 'none';
    const operationTitle = operationType.charAt(0).toUpperCase() + operationType.slice(1);
    container.innerHTML = `
            <div class="progress-section">
                <div class="progress-header">
                    <h3><i class="fas fa-cog fa-spin"></i> ${operationTitle} Progress</h3>
                    <button class="close-progress-btn" type="button" aria-label="Close progress">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div class="progress-content">
                    <div class="progress-bar-container">
                        <div class="progress-bar">
                            <div class="progress-bar-fill"></div>
                        </div>
                        <div class="progress-percentage">0%</div>
                    </div>
                    
                    <div class="progress-status">
                        <div class="status-message">Preparing ${operationType}...</div>
                        <div class="progress-text"></div>
                        <div class="status-details"></div>
                    </div>
                    
                    <div class="progress-stats">
                        <div class="stat-item">
                            <span class="stat-label">Total:</span>
                            <span class="stat-value total">0</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">Processed:</span>
                            <span class="stat-value processed">0</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">Success:</span>
                            <span class="stat-value success">0</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">Failed:</span>
                            <span class="stat-value failed">0</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">Skipped:</span>
                            <span class="stat-value skipped">0</span>
                        </div>
                    </div>
                    
                    <div class="progress-timing">
                        <div class="time-elapsed">
                            <i class="fas fa-clock"></i>
                            <span>Elapsed: <span class="elapsed-value">00:00</span></span>
                        </div>
                        <div class="time-remaining">
                            <i class="fas fa-hourglass-half"></i>
                            <span>ETA: <span class="eta-value">Calculating...</span></span>
                        </div>
                    </div>
                    
                    <div class="progress-actions">
                        <button class="btn btn-secondary cancel-${operationType}-btn" type="button">
                            <i class="fas fa-stop"></i> Cancel ${operationTitle}
                        </button>
                    </div>
                </div>
            </div>
        `;
 
    // Find the appropriate view to append to
    const viewContainer = document.getElementById(`${operationType}-view`);
    if (viewContainer) {
      viewContainer.appendChild(container);
    } else {
      // Fallback to body
      document.body.appendChild(container);
    }
 
    // Set up close button
    const closeBtn = container.querySelector('.close-progress-btn');
    if (closeBtn) {
      closeBtn.addEventListener('click', () => this.hideProgress(operationType));
    }
 
    // Set up cancel button
    const cancelBtn = container.querySelector(`.cancel-${operationType}-btn`);
    if (cancelBtn) {
      cancelBtn.addEventListener('click', () => this.requestCancel(operationType));
    }
    return container;
  }
 
  /**
   * Start a new operation
   */
  startOperation(operationType) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.currentOperation = operationType;
    this.isActive = true;
    this.startTime = Date.now();
 
    // Reset stats
    this.stats = {
      processed: 0,
      successful: 0,
      failed: 0,
      skipped: 0,
      total: options.total || 0,
      errors: []
    };
 
    // Show progress UI
    this.showProgress(operationType);
 
    // Update UI with initial state
    this.updateProgressUI(operationType, {
      message: `Starting ${operationType} operation...`,
      percentage: 0
    });
    this.logger.info('🔧 PROGRESS: Operation started', {
      type: operationType,
      total: this.stats.total,
      options
    });
    this.eventBus.emit('progress:operation-started', {
      type: operationType,
      stats: this.stats,
      options
    });
  }
 
  /**
   * Update progress
   */
  updateProgress(data) {
    if (!this.isActive || !this.currentOperation) return;
 
    // Update stats
    if (data.processed !== undefined) this.stats.processed = data.processed;
    if (data.successful !== undefined) this.stats.successful = data.successful;
    if (data.failed !== undefined) this.stats.failed = data.failed;
    if (data.skipped !== undefined) this.stats.skipped = data.skipped;
    if (data.total !== undefined) this.stats.total = data.total;
    if (data.error) this.stats.errors.push(data.error);
 
    // Calculate progress percentage
    const percentage = this.stats.total > 0 ? Math.round(this.stats.processed / this.stats.total * 100) : 0;
 
    // Calculate timing
    const elapsed = Date.now() - this.startTime;
    const rate = this.stats.processed / (elapsed / 1000); // items per second
    const remaining = this.stats.total - this.stats.processed;
    const eta = rate > 0 ? remaining / rate : 0;
 
    // Update UI
    this.updateProgressUI(this.currentOperation, {
      percentage,
      message: data.message || `Processing ${this.currentOperation}...`,
      progressText: `${this.stats.processed} of ${this.stats.total} processed`,
      elapsed: this.formatTime(elapsed / 1000),
      eta: eta > 0 ? this.formatTime(eta) : 'Calculating...'
    });
    this.logger.debug('🔧 PROGRESS: Progress updated', {
      type: this.currentOperation,
      percentage,
      stats: this.stats
    });
    this.eventBus.emit('progress:updated', {
      type: this.currentOperation,
      percentage,
      stats: this.stats,
      data
    });
  }
 
  /**
   * Complete operation
   */
  completeOperation(data) {
    if (!this.isActive || !this.currentOperation) return;
    const operationType = this.currentOperation;
    const success = this.stats.failed === 0;
    const elapsed = Date.now() - this.startTime;
 
    // Update final stats
    if (data.stats) {
      Object.assign(this.stats, data.stats);
    }
 
    // Update UI with completion state
    this.updateProgressUI(operationType, {
      percentage: 100,
      message: success ? `${operationType.charAt(0).toUpperCase() + operationType.slice(1)} completed successfully!` : `${operationType.charAt(0).toUpperCase() + operationType.slice(1)} completed with ${this.stats.failed} errors`,
      progressText: `Completed ${this.stats.processed} items in ${this.formatTime(elapsed / 1000)}`,
      elapsed: this.formatTime(elapsed / 1000),
      eta: 'Complete'
    });
 
    // Auto-hide after delay for successful operations
    if (success) {
      setTimeout(() => this.hideProgress(operationType), 5000);
    }
    this.isActive = false;
    this.logger.info('🔧 PROGRESS: Operation completed', {
      type: operationType,
      success,
      stats: this.stats,
      duration: elapsed
    });
    this.eventBus.emit('progress:operation-completed', {
      type: operationType,
      success,
      stats: this.stats,
      duration: elapsed,
      data
    });
  }
 
  /**
   * Handle operation error
   */
  handleError(error) {
    if (!this.isActive || !this.currentOperation) return;
    this.stats.errors.push(error);
    this.stats.failed++;
    this.updateProgressUI(this.currentOperation, {
      message: `Error: ${error.message || error.toString()}`,
      statusDetails: `${this.stats.errors.length} error(s) occurred`
    });
    this.logger.error('🔧 PROGRESS: Operation error', {
      type: this.currentOperation,
      error: error.message,
      stats: this.stats
    });
    this.eventBus.emit('progress:error', {
      type: this.currentOperation,
      error,
      stats: this.stats
    });
  }
 
  /**
   * Cancel operation
   */
  cancelOperation(data) {
    if (!this.isActive || !this.currentOperation) return;
    const operationType = this.currentOperation;
    this.updateProgressUI(operationType, {
      message: `${operationType.charAt(0).toUpperCase() + operationType.slice(1)} operation cancelled`,
      statusDetails: 'Operation was cancelled by user'
    });
    this.isActive = false;
    this.logger.info('🔧 PROGRESS: Operation cancelled', {
      type: operationType,
      stats: this.stats
    });
    this.eventBus.emit('progress:operation-cancelled', {
      type: operationType,
      stats: this.stats,
      data
    });
 
    // Hide progress after a short delay
    setTimeout(() => this.hideProgress(operationType), 2000);
  }
 
  /**
   * Request operation cancellation
   */
  requestCancel(operationType) {
    this.logger.info('🔧 PROGRESS: Cancel requested', {
      type: operationType
    });
 
    // Emit cancel request event
    this.eventBus.emit('operation:cancel-requested', {
      type: operationType
    });
 
    // Update UI to show cancelling state
    this.updateProgressUI(operationType, {
      message: 'Cancelling operation...',
      statusDetails: 'Please wait while the operation is cancelled'
    });
  }
 
  /**
   * Update progress UI elements
   */
  updateProgressUI(operationType, updates) {
    const elements = this.progressElements[operationType];
    if (!elements) return;
 
    // Update progress bar
    if (updates.percentage !== undefined && elements.progressBar) {
      elements.progressBar.style.width = `${updates.percentage}%`;
    }
 
    // Update percentage text
    if (updates.percentage !== undefined && elements.percentage) {
      elements.percentage.textContent = `${updates.percentage}%`;
    }
 
    // Update status message
    if (updates.message && elements.statusMessage) {
      elements.statusMessage.textContent = updates.message;
    }
 
    // Update progress text
    if (updates.progressText && elements.progressText) {
      elements.progressText.textContent = updates.progressText;
    }
 
    // Update status details
    if (updates.statusDetails && elements.statusDetails) {
      elements.statusDetails.textContent = updates.statusDetails;
    }
 
    // Update stats
    if (elements.stats) {
      Object.keys(elements.stats).forEach(key => {
        if (elements.stats[key] && this.stats[key] !== undefined) {
          elements.stats[key].textContent = this.stats[key];
        }
      });
    }
 
    // Update timing
    if (elements.timing) {
      if (updates.elapsed && elements.timing.elapsed) {
        elements.timing.elapsed.textContent = updates.elapsed;
      }
      if (updates.eta && elements.timing.eta) {
        elements.timing.eta.textContent = updates.eta;
      }
    }
  }
 
  /**
   * Show progress UI
   */
  showProgress(operationType) {
    const elements = this.progressElements[operationType];
    if (elements && elements.container) {
      elements.container.style.display = 'block';
      elements.container.classList.add('active');
    }
    this.logger.debug('🔧 PROGRESS: Progress UI shown', {
      type: operationType
    });
  }
 
  /**
   * Hide progress UI
   */
  hideProgress(operationType) {
    const elements = this.progressElements[operationType];
    if (elements && elements.container) {
      elements.container.style.display = 'none';
      elements.container.classList.remove('active');
    }
    this.logger.debug('🔧 PROGRESS: Progress UI hidden', {
      type: operationType
    });
  }
 
  /**
   * Format time in seconds to human readable format
   */
  formatTime(seconds) {
    if (seconds < 60) {
      return `${Math.round(seconds)}s`;
    } else if (seconds < 3600) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = Math.round(seconds % 60);
      return `${minutes}m ${remainingSeconds}s`;
    } else {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor(seconds % 3600 / 60);
      return `${hours}h ${minutes}m`;
    }
  }
 
  /**
   * Get current progress state
   */
  getState() {
    return {
      currentOperation: this.currentOperation,
      isActive: this.isActive,
      startTime: this.startTime,
      stats: {
        ...this.stats
      }
    };
  }
 
  /**
   * Reset progress state
   */
  reset() {
    let operationType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    if (operationType) {
      this.hideProgress(operationType);
    } else {
      // Reset all
      Object.keys(this.progressElements).forEach(type => {
        this.hideProgress(type);
      });
    }
    if (!operationType || operationType === this.currentOperation) {
      this.currentOperation = null;
      this.isActive = false;
      this.startTime = null;
      this.stats = {
        processed: 0,
        successful: 0,
        failed: 0,
        skipped: 0,
        total: 0,
        errors: []
      };
    }
    this.logger.info('🔧 PROGRESS: Progress reset', {
      type: operationType || 'all'
    });
  }
 
  /**
   * Destroy the subsystem
   */
  destroy() {
    // Hide all progress UIs
    Object.keys(this.progressElements).forEach(type => {
      this.hideProgress(type);
    });
 
    // Clean up
    this.isActive = false;
    this.currentOperation = null;
    this.progressElements = {};
    this.logger.info('Enhanced Progress Subsystem destroyed');
  }
}
exports.EnhancedProgressSubsystem = EnhancedProgressSubsystem;
var _default = exports.default = EnhancedProgressSubsystem;
 
},{"../utils/browser-logging-service.js":97}],88:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.EnhancedTokenStatusSubsystem = void 0;
var _browserLoggingService = require("../utils/browser-logging-service.js");
/**
 * Enhanced Token Status Subsystem
 * 
 * Modern token status management with better UI updates and styling
 */
 
class EnhancedTokenStatusSubsystem {
  constructor(logger, eventBus, uiManager) {
    this.logger = logger || (0, _browserLoggingService.createLogger)({
      serviceName: 'enhanced-token-status-subsystem',
      enableServer: true
    });
    this.eventBus = eventBus;
    this.uiManager = uiManager;
 
    // Token state
    this.tokenInfo = {
      isValid: false,
      expiresAt: null,
      expiresIn: 0,
      tokenType: 'Bearer',
      lastChecked: null
    };
 
    // UI elements
    this.statusElements = {};
 
    // Update intervals
    this.statusCheckInterval = null;
    this.uiUpdateInterval = null;
 
    // Configuration
    this.CHECK_INTERVAL = 30000; // 30 seconds
    this.UI_UPDATE_INTERVAL = 1000; // 1 second for countdown
 
    this.logger.info('🔑 Enhanced Token Status Subsystem initialized');
  }
 
  /**
   * Initialize the subsystem
   */
  async init() {
    try {
      this.logger.debug('🔑 Initializing Enhanced Token Status Subsystem...');
 
      // Find and cache UI elements
      this.cacheUIElements();
 
      // Set up event listeners
      this.setupEventListeners();
 
      // Start monitoring
      this.startMonitoring();
 
      // Initial token check
      await this.checkTokenStatus();
      this.logger.info('🔑 Enhanced Token Status Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('🔑 Failed to initialize Enhanced Token Status Subsystem', {
        error: error.message,
        stack: error.stack
      });
      throw error;
    }
  }
 
  /**
   * Cache UI elements for faster updates
   */
  cacheUIElements() {
    // Global token status in sidebar
    const globalTokenStatus = document.getElementById('global-token-status');
    if (globalTokenStatus) {
      this.statusElements.global = {
        container: globalTokenStatus,
        icon: globalTokenStatus.querySelector('.global-token-icon'),
        text: globalTokenStatus.querySelector('.global-token-text'),
        countdown: globalTokenStatus.querySelector('.global-token-countdown'),
        indicator: document.getElementById('token-status-indicator'),
        refreshButton: document.getElementById('global-refresh-token'),
        getTokenButton: document.getElementById('global-get-token')
      };
    }
 
    // Token status indicators in other locations
    const indicators = document.querySelectorAll('.token-status-indicator');
    indicators.forEach((indicator, index) => {
      this.statusElements[`indicator_${index}`] = {
        container: indicator,
        icon: indicator.querySelector('.token-status-icon'),
        text: indicator.querySelector('.token-status-text'),
        time: indicator.querySelector('.token-status-time'),
        actions: indicator.querySelector('.token-status-actions')
      };
    });
    this.logger.debug('🔑 UI elements cached', {
      globalStatus: !!this.statusElements.global,
      indicators: Object.keys(this.statusElements).filter(k => k.startsWith('indicator_')).length
    });
  }
 
  /**
   * Set up event listeners
   */
  setupEventListeners() {
    // Listen for token events
    this.eventBus.on('token:refreshed', data => {
      this.logger.info('🔑 TOKEN: Token refreshed event received', data);
      this.handleTokenRefreshed(data);
    });
    this.eventBus.on('token:expired', data => {
      this.logger.warn('🔑 TOKEN: Token expired event received', data);
      this.handleTokenExpired(data);
    });
    this.eventBus.on('token:error', data => {
      this.logger.error('🔑 TOKEN: Token error event received', data);
      this.handleTokenError(data);
    });
    this.eventBus.on('token:obtained', data => {
      this.logger.info('🔑 TOKEN: Token obtained event received', data);
      this.handleTokenObtained(data);
    });
 
    // Listen for settings changes
    this.eventBus.on('settings:updated', () => {
      this.logger.debug('🔑 Settings updated, checking token status');
      this.checkTokenStatus();
    });
 
    // Set up button event listeners
    this.setupButtonListeners();
    this.logger.debug('🔑 Event listeners set up');
  }
 
  /**
   * Set up button event listeners
   */
  setupButtonListeners() {
    // Global refresh button
    if (this.statusElements.global?.refreshButton) {
      this.statusElements.global.refreshButton.addEventListener('click', () => {
        this.logger.info('🔑 TOKEN: Refresh button clicked');
        this.refreshToken();
      });
    }
 
    // Global get token button
    if (this.statusElements.global?.getTokenButton) {
      this.statusElements.global.getTokenButton.addEventListener('click', () => {
        this.logger.info('🔑 TOKEN: Get token button clicked');
        this.getNewToken();
      });
    }
    this.logger.debug('🔑 Button listeners set up');
  }
 
  /**
   * Start monitoring token status
   */
  startMonitoring() {
    // Fixed token status update interval - more frequent checks
    // Check token status more frequently
    this.statusCheckInterval = setInterval(() => {
      this.checkTokenStatus();
    }, 10000); // Check every 10 seconds instead of 30
 
    // Update UI countdown every second
    this.uiUpdateInterval = setInterval(() => {
      this.updateCountdown();
    }, 1000);
    this.logger.debug('🔑 Token monitoring started with improved frequency');
  }
 
  /**
   * Stop monitoring
   */
  stopMonitoring() {
    if (this.statusCheckInterval) {
      clearInterval(this.statusCheckInterval);
      this.statusCheckInterval = null;
    }
    if (this.uiUpdateInterval) {
      clearInterval(this.uiUpdateInterval);
      this.uiUpdateInterval = null;
    }
    this.logger.debug('🔑 Token monitoring stopped');
  }
 
  /**
   * Check current token status
   */
  async checkTokenStatus() {
    try {
      this.logger.debug('🔑 Checking token status...');
 
      // Try to get token info from various sources
      const tokenInfo = await this.getTokenInfo();
 
      // Update internal state
      this.tokenInfo = {
        ...this.tokenInfo,
        ...tokenInfo,
        lastChecked: Date.now()
      };
 
      // Update UI
      this.updateUI();
 
      // Log token status
      this.logTokenStatus();
 
      // Emit event
      this.eventBus.emit('token-status:updated', this.tokenInfo);
    } catch (error) {
      this.logger.error('🔑 Error checking token status', {
        error: error.message
      });
 
      // Set error state
      this.tokenInfo = {
        ...this.tokenInfo,
        isValid: false,
        error: error.message,
        lastChecked: Date.now()
      };
      this.updateUI();
    }
  }
 
  /**
   * Get token information from various sources
   */
  async getTokenInfo() {
    // Try to get from global token manager first
    if (window.app?.subsystems?.globalTokenManager) {
      try {
        const status = window.app.subsystems.globalTokenManager.getTokenStatus();
        if (status) {
          return {
            isValid: status.isValid,
            expiresAt: status.expiresAt,
            expiresIn: status.expiresIn,
            tokenType: status.tokenType || 'Bearer'
          };
        }
      } catch (error) {
        this.logger.debug('🔑 Could not get status from global token manager', error);
      }
    }
 
    // Try to get from token manager
    if (window.app?.tokenManager) {
      try {
        const status = window.app.tokenManager.getTokenStatus();
        if (status) {
          return {
            isValid: status.isValid,
            expiresAt: status.expiresAt,
            expiresIn: status.expiresIn,
            tokenType: status.tokenType || 'Bearer'
          };
        }
      } catch (error) {
        this.logger.debug('🔑 Could not get status from token manager', error);
      }
    }
 
    // Try to get from localStorage
    try {
      const token = localStorage.getItem('pingone_worker_token');
      const expiry = localStorage.getItem('pingone_token_expiry');
      if (token && expiry) {
        const expiryTime = parseInt(expiry, 10);
        const currentTime = Math.floor(Date.now() / 1000);
        const expiresIn = Math.max(0, expiryTime - currentTime);
        return {
          isValid: expiresIn > 0,
          expiresAt: new Date(expiryTime * 1000).toISOString(),
          expiresIn: expiresIn,
          tokenType: 'Bearer'
        };
      }
    } catch (error) {
      this.logger.debug('🔑 Could not get token from localStorage', error);
    }
 
    // Default to no token
    return {
      isValid: false,
      expiresAt: null,
      expiresIn: 0,
      tokenType: 'Bearer'
    };
  }
 
  /**
   * Update UI elements
   */
  updateUI() {
    const status = this.determineStatus();
 
    // Update global token status
    if (this.statusElements.global) {
      this.updateGlobalStatus(status);
    }
 
    // Update other indicators
    Object.keys(this.statusElements).forEach(key => {
      if (key.startsWith('indicator_')) {
        this.updateIndicator(this.statusElements[key], status);
      }
    });
    this.logger.debug('🔑 UI updated', {
      status: status.type
    });
  }
 
  /**
   * Determine current status type and styling
   */
  determineStatus() {
    if (this.tokenInfo.error) {
      return {
        type: 'error',
        icon: '❌',
        text: 'Token Error',
        className: 'error',
        color: '#dc3545'
      };
    }
    if (!this.tokenInfo.isValid || this.tokenInfo.expiresIn <= 0) {
      return {
        type: 'expired',
        icon: '🔒',
        text: 'Token Expired',
        className: 'expired',
        color: '#dc3545'
      };
    }
    if (this.tokenInfo.expiresIn <= 300) {
      // 5 minutes
      return {
        type: 'expiring',
        icon: '⚠️',
        text: 'Token Expiring',
        className: 'expiring',
        color: '#ffc107'
      };
    }
    return {
      type: 'valid',
      icon: '✅',
      text: 'Token Valid',
      className: 'valid',
      color: '#28a745'
    };
  }
 
  /**
   * Update global token status in sidebar
   */
  updateGlobalStatus(status) {
    const elements = this.statusElements.global;
    if (!elements) return;
 
    // Update container class
    if (elements.container) {
      elements.container.className = `global-token-status ${status.className}`;
    }
 
    // Update icon
    if (elements.icon) {
      elements.icon.textContent = status.icon;
    }
 
    // Update text
    if (elements.text) {
      elements.text.textContent = status.text;
    }
 
    // Update countdown
    if (elements.countdown) {
      if (this.tokenInfo.isValid && this.tokenInfo.expiresIn > 0) {
        const minutes = Math.floor(this.tokenInfo.expiresIn / 60);
        elements.countdown.textContent = `${minutes}m`;
      } else {
        elements.countdown.textContent = '';
      }
    }
 
    // Update indicator dot
    if (elements.indicator) {
      elements.indicator.className = `token-status-indicator ${status.className}`;
      elements.indicator.style.color = status.color;
      elements.indicator.textContent = '●';
      elements.indicator.title = `${status.text} - ${this.formatTimeRemaining()}`;
    }
 
    // Show/hide buttons based on status
    if (elements.refreshButton) {
      elements.refreshButton.style.display = this.tokenInfo.isValid ? 'inline-block' : 'none';
    }
    if (elements.getTokenButton) {
      elements.getTokenButton.style.display = !this.tokenInfo.isValid ? 'inline-block' : 'none';
    }
  }
 
  /**
   * Update indicator element
   */
  updateIndicator(elements, status) {
    if (!elements || !elements.container) return;
 
    // Update container class
    elements.container.className = `token-status-indicator ${status.className}`;
 
    // Update icon
    if (elements.icon) {
      elements.icon.textContent = status.icon;
    }
 
    // Update text
    if (elements.text) {
      elements.text.textContent = status.text;
    }
 
    // Update time
    if (elements.time) {
      elements.time.textContent = this.formatTimeRemaining();
    }
  }
 
  /**
   * Update countdown display
   */
  updateCountdown() {
    if (!this.tokenInfo.isValid || this.tokenInfo.expiresIn <= 0) return;
 
    // Recalculate time remaining
    if (this.tokenInfo.expiresAt) {
      const expiryTime = new Date(this.tokenInfo.expiresAt).getTime();
      const currentTime = Date.now();
      const expiresIn = Math.max(0, Math.floor((expiryTime - currentTime) / 1000));
      this.tokenInfo.expiresIn = expiresIn;
 
      // Update countdown in global status
      if (this.statusElements.global?.countdown) {
        const minutes = Math.floor(expiresIn / 60);
        this.statusElements.global.countdown.textContent = expiresIn > 0 ? `${minutes}m` : '';
      }
 
      // Update time in indicators
      Object.keys(this.statusElements).forEach(key => {
        if (key.startsWith('indicator_') && this.statusElements[key].time) {
          this.statusElements[key].time.textContent = this.formatTimeRemaining();
        }
      });
 
      // Check if token expired
      if (expiresIn <= 0 && this.tokenInfo.isValid) {
        this.handleTokenExpired();
      }
    }
  }
 
  /**
   * Format time remaining for display
   */
  formatTimeRemaining() {
    if (!this.tokenInfo.isValid || this.tokenInfo.expiresIn <= 0) {
      return 'Expired';
    }
    const minutes = Math.floor(this.tokenInfo.expiresIn / 60);
    const seconds = this.tokenInfo.expiresIn % 60;
    if (minutes > 0) {
      return `${minutes}m ${seconds}s`;
    } else {
      return `${seconds}s`;
    }
  }
 
  /**
   * Log current token status
   */
  logTokenStatus() {
    const logData = {
      isValid: this.tokenInfo.isValid,
      expiresIn: this.tokenInfo.expiresIn,
      expiresInMinutes: Math.floor(this.tokenInfo.expiresIn / 60),
      expiresAt: this.tokenInfo.expiresAt,
      tokenType: this.tokenInfo.tokenType,
      lastChecked: new Date(this.tokenInfo.lastChecked).toISOString()
    };
    if (this.tokenInfo.isValid) {
      this.logger.info('🔑 TOKEN: Token status check - Valid', logData);
    } else {
      this.logger.warn('🔑 TOKEN: Token status check - Invalid', logData);
    }
  }
 
  /**
   * Handle token refreshed event
   */
  handleTokenRefreshed(data) {
    this.tokenInfo = {
      ...this.tokenInfo,
      isValid: true,
      expiresIn: data.expiresIn || 3600,
      expiresAt: data.expiresAt || new Date(Date.now() + (data.expiresIn || 3600) * 1000).toISOString(),
      tokenType: data.tokenType || 'Bearer',
      error: null,
      lastChecked: Date.now()
    };
    this.updateUI();
    this.logger.info('🔑 TOKEN: Token refreshed successfully', {
      expiresIn: this.tokenInfo.expiresIn,
      expiresInMinutes: Math.floor(this.tokenInfo.expiresIn / 60)
    });
  }
 
  /**
   * Handle token expired event
   */
  handleTokenExpired(data) {
    this.tokenInfo = {
      ...this.tokenInfo,
      isValid: false,
      expiresIn: 0,
      error: 'Token expired',
      lastChecked: Date.now()
    };
    this.updateUI();
    this.logger.warn('🔑 TOKEN: Token expired', data);
  }
 
  /**
   * Handle token error event
   */
  handleTokenError(data) {
    this.tokenInfo = {
      ...this.tokenInfo,
      isValid: false,
      error: data.error || 'Token error',
      lastChecked: Date.now()
    };
    this.updateUI();
    this.logger.error('🔑 TOKEN: Token error', data);
  }
 
  /**
   * Handle token obtained event
   */
  handleTokenObtained(data) {
    this.tokenInfo = {
      ...this.tokenInfo,
      isValid: true,
      expiresIn: data.expiresIn || 3600,
      expiresAt: data.expiresAt || new Date(Date.now() + (data.expiresIn || 3600) * 1000).toISOString(),
      tokenType: data.tokenType || 'Bearer',
      error: null,
      lastChecked: Date.now()
    };
    this.updateUI();
    this.logger.info('🔑 TOKEN: New token obtained', {
      expiresIn: this.tokenInfo.expiresIn,
      expiresInMinutes: Math.floor(this.tokenInfo.expiresIn / 60)
    });
  }
 
  /**
   * Refresh token
   */
  async refreshToken() {
    try {
      this.logger.info('🔑 TOKEN: Refreshing token...');
 
      // Try global token manager first
      if (window.app?.subsystems?.globalTokenManager?.refreshToken) {
        await window.app.subsystems.globalTokenManager.refreshToken();
        return;
      }
 
      // Try token manager
      if (window.app?.tokenManager?.refreshToken) {
        await window.app.tokenManager.refreshToken();
        return;
      }
 
      // Fallback to API call
      const response = await fetch('/api/pingone/token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      if (response.ok) {
        const data = await response.json();
        this.handleTokenRefreshed(data);
      } else {
        throw new Error(`Token refresh failed: ${response.status}`);
      }
    } catch (error) {
      this.logger.error('🔑 TOKEN: Failed to refresh token', {
        error: error.message
      });
      this.handleTokenError({
        error: error.message
      });
    }
  }
 
  /**
   * Get new token
   */
  async getNewToken() {
    try {
      this.logger.info('🔑 TOKEN: Getting new token...');
 
      // Navigate to settings or show credentials modal
      if (window.app?.subsystems?.navigation) {
        window.app.subsystems.navigation.navigateToView('settings');
      } else {
        // Fallback
        window.location.hash = 'settings';
      }
    } catch (error) {
      this.logger.error('🔑 TOKEN: Failed to get new token', {
        error: error.message
      });
    }
  }
 
  /**
   * Get current token status
   */
  getStatus() {
    return {
      ...this.tokenInfo
    };
  }
 
  /**
   * Destroy the subsystem
   */
  destroy() {
    this.stopMonitoring();
    this.statusElements = {};
    this.logger.info('🔑 Enhanced Token Status Subsystem destroyed');
  }
}
exports.EnhancedTokenStatusSubsystem = EnhancedTokenStatusSubsystem;
var _default = exports.default = EnhancedTokenStatusSubsystem;
 
},{"../utils/browser-logging-service.js":97}],89:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ExportSubsystem = void 0;
/**
 * Export Management Subsystem
 * 
 * Handles all user export operations with proper separation of concerns.
 * Manages export configuration, progress tracking, and file generation.
 */
 
class ExportSubsystem {
  constructor(logger, uiManager, localClient, settingsManager, eventBus, populationService) {
    this.logger = logger;
    this.uiManager = uiManager;
    this.localClient = localClient;
    this.settingsManager = settingsManager;
    this.eventBus = eventBus;
    this.populationService = populationService;
 
    // Export state management
    this.isExporting = false;
    this.selectedPopulationId = null;
    this.selectedPopulationName = null;
    this.logger.info('Export Subsystem initialized');
 
    // Set up event listeners for cross-subsystem communication
    this.setupCrossSubsystemEvents();
  }
 
  /**
   * Initialize the export subsystem
   */
  async init() {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const initAction = async () => {
      this.setupEventListeners();
      await this.loadPopulations();
      this.logger.info('Export Subsystem initialized successfully');
    };
    await errorHandler.wrapAsync(initAction, 'Initialize Export Subsystem', 'Failed to Initialize Export Subsystem' // Custom error message for UI
    )();
  }
 
  /**
   * Set up event listeners for export-related elements
   */
  setupEventListeners() {
    // Initialize utilities for safe DOM operations
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_BTN: 'export-btn',
        EXPORT_POPULATION_SELECT: 'export-population-select',
        EXPORT_FORMAT: 'export-format'
      }
    };
 
    // Export button
    const exportBtn = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_BTN);
    if (exportBtn) {
      safeDOM.addEventListener(exportBtn, 'click', errorHandler.wrapAsyncEventHandler(async e => {
        e.preventDefault();
        await this.startExport();
      }, 'Export button click'));
    }
 
    // Population selection change
    const populationSelect = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_POPULATION_SELECT);
    if (populationSelect) {
      safeDOM.addEventListener(populationSelect, 'change', errorHandler.wrapEventHandler(e => {
        this.handlePopulationChange(e.target.value);
      }, 'Export population change'));
    }
 
    // Export format selection
    const formatSelect = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_FORMAT);
    if (formatSelect) {
      safeDOM.addEventListener(formatSelect, 'change', errorHandler.wrapEventHandler(e => {
        this.handleFormatChange(e.target.value);
      }, 'Export format change'));
    }
  }
 
  /**
   * Start the export process
   */
  async startExport() {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    if (this.isExporting) {
      this.logger.warn('Export already in progress');
      return;
    }
    this.isExporting = true;
    this.logger.info('Starting export process');
    try {
      const exportAction = async () => {
        // Validate prerequisites
        if (!(await this.validateExportPrerequisites())) {
          return; // Validation failed, error already shown.
        }
 
        // Get export configuration
        const config = this.getExportConfiguration();
 
        // Show progress UI
        this.uiManager.showProgress('Exporting...');
 
        // Execute export
        await this.executeExport(config);
      };
      await errorHandler.wrapAsync(exportAction, 'Start export process', 'The export failed. Please check the application logs for more details.')();
    } finally {
      // This block ensures that the UI is always reset, even if validation fails or an error occurs.
      this.isExporting = false;
      this.uiManager.hideProgress();
    }
  }
 
  /**
   * Validate export prerequisites
   */
  async validateExportPrerequisites() {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_POPULATION_SELECT: 'export-population-select'
      }
    };
    const validationAction = async () => {
      // Check for valid token
      const hasValidToken = await this.checkTokenStatus();
      if (!hasValidToken) {
        this.logger.warn('Export cancelled - no valid token');
        this.uiManager.showError('Authentication Required', 'Please get a valid token first');
        return false;
      }
 
      // Check population selection
      const populationSelect = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_POPULATION_SELECT);
      if (!populationSelect || !populationSelect.value) {
        this.uiManager.showError('No Population Selected', 'Please select a population to export');
        return false;
      }
      return true;
    };
    return await errorHandler.wrapAsync(validationAction, 'Validate export prerequisites')();
  }
 
  /**
   * Get export configuration from form
   */
  getExportConfiguration() {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_POPULATION_SELECT: 'export-population-select',
        EXPORT_FORMAT: 'export-format',
        INCLUDE_HEADERS: 'include-headers',
        LIMIT_USERS: 'limit-users',
        USER_LIMIT: 'user-limit'
      }
    };
    const getAction = () => {
      const populationSelect = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_POPULATION_SELECT);
      const formatSelect = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_FORMAT);
      const includeHeaders = safeDOM.selectById(UI_CONFIG.SELECTORS.INCLUDE_HEADERS);
      const limitUsers = safeDOM.selectById(UI_CONFIG.SELECTORS.LIMIT_USERS);
      const userLimit = safeDOM.selectById(UI_CONFIG.SELECTORS.USER_LIMIT);
      const isLimitEnabled = limitUsers ? limitUsers.checked : false;
      return {
        populationId: populationSelect ? populationSelect.value : '',
        populationName: populationSelect && populationSelect.selectedIndex >= 0 ? populationSelect.options[populationSelect.selectedIndex].text : '',
        format: formatSelect ? formatSelect.value : 'csv',
        includeHeaders: includeHeaders ? includeHeaders.checked : true,
        limitUsers: isLimitEnabled,
        userLimit: isLimitEnabled ? parseInt(userLimit?.value, 10) || 100 : null,
        timestamp: new Date().toISOString()
      };
    };
    return errorHandler.wrapSync(getAction, 'Get export configuration')();
  }
 
  /**
   * Execute the export process
   */
  async executeExport(config) {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const exportAction = async () => {
      this.logger.info('Executing export with config', config);
 
      // Send export request
      const response = await this.localClient.post('/api/export', config);
      if (!response.success) {
        throw new Error(response.error || 'Export failed');
      }
 
      // Handle file download
      if (response.downloadUrl) {
        this.downloadFile(response.downloadUrl, response.filename);
      } else if (response.data) {
        this.downloadData(response.data, config.format, config.populationName);
      }
      this.logger.info('Export completed successfully');
      this.uiManager.showSuccess('Export completed successfully');
    };
 
    // Errors will be caught and re-thrown, to be handled by the caller (startExport)
    await errorHandler.wrapAsync(exportAction, 'Execute export', 'Failed to communicate with the server during export. Please check your connection and try again.', {
      rethrow: true
    } // Rethrow to allow the caller to handle UI cleanup
    )();
  }
 
  /**
   * Download file from URL
   */
  downloadFile(url, filename) {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const downloadAction = () => {
      const link = safeDOM.createElement('a');
      if (!link) return; // createElement can fail
 
      link.href = url;
      link.download = filename || `export_${Date.now()}.csv`;
      safeDOM.appendChild(document.body, link);
      link.click(); // Direct click is generally safe here
      safeDOM.removeChild(document.body, link);
      this.logger.info('Successfully triggered file download', {
        filename
      });
    };
    errorHandler.wrapSync(downloadAction, 'Download file from URL', 'Failed to trigger file download. Please check browser permissions and try again.')();
  }
 
  /**
   * Download data as file
   */
  downloadData(data, format, populationName) {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const downloadDataAction = () => {
      let content, mimeType, extension;
      switch (format) {
        case 'json':
          content = JSON.stringify(data, null, 2);
          mimeType = 'application/json';
          extension = 'json';
          break;
        case 'csv':
        default:
          content = this.convertToCSV(data);
          mimeType = 'text/csv';
          extension = 'csv';
          break;
      }
      const blob = new Blob([content], {
        type: mimeType
      });
      const url = URL.createObjectURL(blob);
      const filename = `${populationName || 'export'}_${Date.now()}.${extension}`;
      try {
        this.downloadFile(url, filename);
      } finally {
        // Revoke the object URL to free up memory, regardless of success
        URL.revokeObjectURL(url);
        this.logger.debug('Revoked object URL for downloaded file', {
          url
        });
      }
    };
    errorHandler.wrapSync(downloadDataAction, 'Download data as file', 'Failed to prepare data for download. The data may be invalid or too large.')();
  }
 
  /**
   * Convert data to CSV format
   */
  convertToCSV(data) {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const convertAction = () => {
      if (!Array.isArray(data) || data.length === 0) {
        return '';
      }
 
      // Get headers from first object
      const headers = Object.keys(data[0]);
      const csvHeaders = headers.join(',');
 
      // Convert data rows
      const csvRows = data.map(row => {
        return headers.map(header => {
          const value = row[header];
          // Escape commas and quotes
          if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
            return `"${value.replace(/"/g, '""')}"`;
          }
          return value || '';
        }).join(',');
      });
      return [csvHeaders, ...csvRows].join('\n');
    };
    return errorHandler.wrapSync(convertAction, 'Convert data to CSV', 'Failed to convert data to CSV format. The data might be structured incorrectly.')() || ''; // Ensure empty string on failure
  }
 
  /**
   * Load populations for dropdown
   * CRITICAL: This method loads populations for export functionality
   * DO NOT modify API endpoint without verifying it matches server routes
   * Last debugged: 2025-07-21 - Added debug logging for population loading issues
   */
  async loadPopulations() {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const loadAction = async () => {
      this.logger.info('🔄 EXPORT: Loading populations for export dropdown...');
      const response = await this.localClient.get('/api/populations');
      this.logger.debug('🔄 EXPORT: Populations API response:', {
        success: response.success,
        populationCount: response.populations?.length || 0,
        hasPopulations: !!response.populations
      });
      if (response.success && response.populations) {
        this.logger.info(`🔄 EXPORT: Successfully loaded ${response.populations.length} populations`);
        this.populateDropdown(response.populations);
      } else {
        // Let the errorHandler handle the UI notification by throwing an error.
        throw new Error('Invalid or empty response from populations API');
      }
    };
    await errorHandler.wrapAsync(loadAction, 'Load populations for export', 'Failed to load populations from the server. Please check your connection and refresh the page.')();
  }
 
  /**
   * Populate the population dropdown
   * CRITICAL: This method populates the export population dropdown with loaded data
   * DO NOT change the dropdown element ID without updating HTML templates
   * Last debugged: 2025-07-21 - Added debug logging for dropdown population issues
   */
  populateDropdown(populations) {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_POPULATION_SELECT: 'export-population-select'
      }
    };
    const populateAction = () => {
      this.logger.debug('🔄 EXPORT: Populating export population dropdown...', {
        populationCount: populations?.length || 0,
        populations: populations?.map(p => ({
          id: p.id,
          name: p.name
        })) || []
      });
      const select = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_POPULATION_SELECT);
      if (!select) {
        // safeDOM already logs the error, so we can just return.
        return;
      }
 
      // Clear existing options safely
      safeDOM.setHTML(select, '<option value="">Select Population</option>');
      this.logger.debug('🔄 EXPORT: Cleared existing dropdown options');
 
      // Add population options
      let optionsAdded = 0;
      populations.forEach(pop => {
        if (pop && pop.id && pop.name) {
          const option = safeDOM.createElement('option');
          if (option) {
            option.value = pop.id;
            safeDOM.setText(option, pop.name); // Use setText for safety
            safeDOM.appendChild(select, option);
            optionsAdded++;
          }
        } else {
          this.logger.warn('🔄 EXPORT: Skipping invalid population data', {
            population: pop
          });
        }
      });
      this.logger.info(`🔄 EXPORT: Successfully populated dropdown with ${optionsAdded} population options`);
    };
    errorHandler.wrapSync(populateAction, 'Populate export dropdown', 'Failed to display populations in the dropdown. The application may be in an inconsistent state.')();
  }
 
  /**
   * Handle population selection change
   */
  handlePopulationChange(populationId) {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_POPULATION_SELECT: 'export-population-select'
      }
    };
    const changeAction = () => {
      this.selectedPopulationId = populationId;
      const select = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_POPULATION_SELECT);
      if (select && select.selectedIndex >= 0) {
        this.selectedPopulationName = select.options[select.selectedIndex]?.text || '';
      } else {
        this.selectedPopulationName = '';
      }
      this.logger.info('Population selection changed', {
        id: this.selectedPopulationId,
        name: this.selectedPopulationName
      });
 
      // Update UI based on selection
      this.updateExportOptions();
    };
    errorHandler.wrapSync(changeAction, 'Handle population change', 'Failed to update the UI after population change. Please try again.')();
  }
 
  /**
   * Handle export format change
   */
  handleFormatChange(format) {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const changeAction = () => {
      this.logger.info('Export format changed', {
        format
      });
 
      // Update UI based on format selection
      this.updateFormatOptions(format);
    };
    errorHandler.wrapSync(changeAction, 'Handle format change', 'Failed to update UI for the selected format. Please try again.')();
  }
 
  /**
   * Update export options based on population selection
   */
  updateExportOptions() {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_BTN: 'export-btn'
      }
    };
    const updateAction = () => {
      const exportBtn = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_BTN);
      if (this.selectedPopulationId) {
        safeDOM.enable(exportBtn);
        this.showExportOptions();
      } else {
        safeDOM.disable(exportBtn);
        this.hideExportOptions();
      }
    };
    errorHandler.wrapSync(updateAction, 'Update export options', 'Failed to update export UI options. The UI may be in an inconsistent state.')();
  }
 
  /**
   * Update format-specific options
   */
  updateFormatOptions(format) {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        HEADERS_OPTION: 'headers-option'
      }
    };
    const updateAction = () => {
      const headersOption = safeDOM.selectById(UI_CONFIG.SELECTORS.HEADERS_OPTION);
      if (headersOption) {
        headersOption.style.display = format === 'csv' ? 'block' : 'none';
      }
    };
    errorHandler.wrapSync(updateAction, 'Update format options', 'Failed to update format-specific UI options. The UI may be in an inconsistent state.')();
  }
 
  /**
   * Show export options
   */
  showExportOptions() {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_OPTIONS: 'export-options'
      }
    };
    const showOptionsAction = () => {
      const optionsContainer = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_OPTIONS);
      safeDOM.show(optionsContainer);
    };
    errorHandler.wrapSync(showOptionsAction, 'Show export options', 'Failed to show export options. The UI may be in an inconsistent state.')();
  }
 
  /**
   * Hide export options
   */
  hideExportOptions() {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_OPTIONS: 'export-options'
      }
    };
    const hideOptionsAction = () => {
      const optionsContainer = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_OPTIONS);
      safeDOM.hide(optionsContainer);
    };
    errorHandler.wrapSync(hideOptionsAction, 'Hide export options', 'Failed to hide export options. The UI may be in an inconsistent state.')();
  }
 
  /**
   * Show export progress
   */
  showExportProgress() {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_PROGRESS: 'export-progress',
        EXPORT_BTN: 'export-btn'
      },
      MESSAGES: {
        EXPORTING: 'Exporting...'
      }
    };
    const showProgressAction = () => {
      const progressContainer = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_PROGRESS);
      safeDOM.show(progressContainer);
      const exportBtn = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_BTN);
      safeDOM.disable(exportBtn);
      safeDOM.setText(exportBtn, UI_CONFIG.MESSAGES.EXPORTING);
    };
    errorHandler.wrapSync(showProgressAction, 'Show export progress', 'Failed to show export progress. The UI may be in an inconsistent state.')();
  }
 
  /**
   * Hide export progress
   */
  hideExportProgress() {
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        EXPORT_PROGRESS: 'export-progress',
        EXPORT_BTN: 'export-btn'
      },
      MESSAGES: {
        EXPORT_USERS: 'Export Users'
      }
    };
    const hideProgressAction = () => {
      const progressContainer = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_PROGRESS);
      safeDOM.hide(progressContainer);
      const exportBtn = safeDOM.selectById(UI_CONFIG.SELECTORS.EXPORT_BTN);
      safeDOM.enable(exportBtn);
      safeDOM.setText(exportBtn, UI_CONFIG.MESSAGES.EXPORT_USERS);
    };
    errorHandler.wrapSync(hideProgressAction, 'Hide export progress', 'Failed to hide export progress. Please refresh the page if the UI is unresponsive.')();
  }
 
  /**
   * Check token status
   */
  async checkTokenStatus() {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const checkAction = async () => {
      const response = await this.localClient.get('/api/v1/auth/status');
      return response.valid;
    };
    try {
      // Use wrapAsync to handle logging, but catch the error to return a boolean.
      return await errorHandler.wrapAsync(checkAction, 'Check token status')();
    } catch (error) {
      // Error is already logged by the handler. Return false as per original logic.
      return false;
    }
  }
 
  /**
   * Set up cross-subsystem event listeners
   */
  setupCrossSubsystemEvents() {
    if (!this.eventBus) {
      this.logger.warn('EventBus not available for cross-subsystem events');
      return;
    }
 
    // Listen for token expiration events
    this.eventBus.on('tokenExpired', data => {
      this.logger.warn('Token expired during export operation');
      if (this.isExporting) {
        this.isExporting = false;
        this.hideExportProgress();
        this.uiManager.showError('Session Expired', 'Your authentication token expired during the export. Please re-authenticate and try again.');
      }
    });
 
    // Listen for token error events
    this.eventBus.on('tokenError', data => {
      this.logger.error('Token error detected', data);
      if (this.isExporting) {
        this.isExporting = false;
        this.hideExportProgress();
        this.uiManager.showError('Authentication Error', `Authentication failed: ${data.error}`);
      }
    });
 
    // Listen for token refresh events
    this.eventBus.on('tokenRefreshed', data => {
      this.logger.info('Token refreshed successfully');
      // Token refresh is handled automatically, just log for now
    });
 
    // Listen for population change events
    this.eventBus.on('populationsChanged', data => {
      this.logger.info('Populations changed, refreshing export dropdown', {
        count: data.count
      });
      this.refreshPopulationDropdown();
    });
    this.logger.debug('Cross-subsystem event listeners set up for ExportSubsystem');
  }
 
  /**
   * Refresh the population dropdown for export
   */
  refreshPopulationDropdown() {
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const refreshAction = async () => {
      if (!this.populationService) {
        this.logger.warn('PopulationService not available for dropdown refresh');
        return; // Exit gracefully if the service is not available
      }
      await this.populationService.populateDropdown('export-population-select', {
        includeEmpty: true,
        emptyText: 'Select a population'
      });
      this.logger.debug('Export population dropdown refreshed successfully');
    };
 
    // The errorHandler will catch any failures from populateDropdown
    errorHandler.wrapAsync(refreshAction, 'Refresh export population dropdown', 'Failed to refresh the population list. Please check your connection or try again.')();
  }
}
exports.ExportSubsystem = ExportSubsystem;
 
},{}],90:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.GlobalTokenManagerSubsystem = void 0;
/**
 * Global Token Manager Subsystem
 * 
 * Provides a prominent global token status display in the sidebar
 * with real-time countdown timer and enhanced visibility across all windows.
 * 
 * Follows the subsystem architecture pattern with proper lifecycle management,
 * EventBus integration, and consistent initialization.
 */
 
class GlobalTokenManagerSubsystem {
  constructor(logger, eventBus) {
    this.logger = logger || console;
    this.eventBus = eventBus;
 
    // Subsystem state
    this.isInitialized = false;
    this.isDestroyed = false;
 
    // Timer for updating token status
    this.globalTokenTimer = null;
    this.updateInterval = 1000; // 1 second
 
    // Bind methods
    this.init = this.init.bind(this);
    this.destroy = this.destroy.bind(this);
    this.updateGlobalTokenStatus = this.updateGlobalTokenStatus.bind(this);
    this.setupGlobalTokenEventListeners = this.setupGlobalTokenEventListeners.bind(this);
    this.startGlobalTokenTimer = this.startGlobalTokenTimer.bind(this);
    this.getNewToken = this.getNewToken.bind(this);
    this.logger.debug('Global Token Manager Subsystem created');
  }
 
  /**
   * Initialize the subsystem
   */
  async init() {
    if (this.isInitialized) {
      this.logger.warn('Global Token Manager Subsystem already initialized');
      return;
    }
    try {
      this.logger.info('Initializing Global Token Manager Subsystem...');
 
      // Wait for DOM to be ready and token status element to exist
      await this.waitForTokenStatusElement();
 
      // Prevent conflicts with other token status systems
      this.preventTokenStatusConflicts();
 
      // Set up event listeners
      this.setupGlobalTokenEventListeners();
 
      // Set up EventBus listeners
      this.setupEventBusListeners();
 
      // Start the update timer
      this.startGlobalTokenTimer();
 
      // Initial status update
      this.updateGlobalTokenStatus();
      this.isInitialized = true;
      this.logger.info('Global Token Manager Subsystem initialized successfully');
 
      // Emit initialization event
      if (this.eventBus) {
        this.eventBus.emit('globalTokenManager:initialized');
      }
    } catch (error) {
      this.logger.error('Failed to initialize Global Token Manager Subsystem', {
        error: error.message,
        stack: error.stack
      });
      throw error;
    }
  }
 
  /**
   * Destroy the subsystem and clean up resources
   */
  async destroy() {
    if (this.isDestroyed) {
      return;
    }
    this.logger.info('Destroying Global Token Manager Subsystem...');
 
    // Stop the timer
    if (this.globalTokenTimer) {
      clearInterval(this.globalTokenTimer);
      this.globalTokenTimer = null;
    }
 
    // Remove event listeners
    this.removeEventListeners();
 
    // Clean up DOM protection
    if (this.mutationObserver) {
      this.mutationObserver.disconnect();
      this.mutationObserver = null;
    }
 
    // Restore original UIManager methods
    this.restoreOriginalMethods();
 
    // Mark as destroyed
    this.isDestroyed = true;
    this.isInitialized = false;
 
    // Emit destruction event
    if (this.eventBus) {
      this.eventBus.emit('globalTokenManager:destroyed');
    }
    this.logger.info('Global Token Manager Subsystem destroyed');
  }
 
  /**
   * Wait for token status element to be available in DOM
   */
  async waitForTokenStatusElement() {
    const maxAttempts = 100;
    const delay = 100;
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      // Check if DOM is ready
      if (document.readyState !== 'complete' && document.readyState !== 'interactive') {
        this.logger.debug(`DOM not ready (${document.readyState}), waiting...`);
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      const element = document.getElementById('global-token-status');
      if (element) {
        // Verify all required child elements exist (they may be nested)
        const countdown = element.querySelector('.global-token-countdown');
        const icon = element.querySelector('.global-token-icon');
        const text = element.querySelector('.global-token-text');
 
        // If the main element exists, consider it ready even if some child elements are missing
        // The child elements will be populated by other methods
        if (element.id === 'global-token-status') {
          this.logger.debug('Global token status element found and ready', {
            attempt,
            elementId: element.id,
            hasCountdown: !!countdown,
            hasIcon: !!icon,
            hasText: !!text
          });
          return element;
        }
      } else {
        this.logger.debug(`Global token status element not found (attempt ${attempt}/${maxAttempts})`);
      }
      await new Promise(resolve => setTimeout(resolve, delay));
    }
    this.logger.error('Global token status element not found after waiting', {
      domState: document.readyState,
      bodyExists: !!document.body,
      sidebarExists: !!document.querySelector('.sidebar'),
      allElementsWithId: Array.from(document.querySelectorAll('[id]')).map(el => el.id)
    });
    throw new Error('Global token status element not found after waiting');
  }
 
  /**
   * Prevent conflicts with other token status systems
   */
  preventTokenStatusConflicts() {
    this.logger.debug('Preventing token status conflicts...');
 
    // Mark our global token status element as protected
    const statusElement = document.getElementById('global-token-status');
    if (statusElement) {
      statusElement.setAttribute('data-protected', 'true');
      statusElement.setAttribute('data-managed-by', 'GlobalTokenManagerSubsystem');
 
      // Add a mutation observer to prevent other systems from modifying our element
      this.setupDOMProtection(statusElement);
    }
 
    // Override conflicting UIManager methods if they exist
    this.overrideConflictingMethods();
    this.logger.debug('Token status conflicts prevention set up');
  }
 
  /**
   * Set up DOM protection to prevent other systems from modifying our widget
   */
  setupDOMProtection(element) {
    if (!window.MutationObserver) {
      return; // Skip if MutationObserver not supported
    }
    this.mutationObserver = new MutationObserver(mutations => {
      mutations.forEach(mutation => {
        // If our element was removed or modified by another system, restore it
        if (mutation.type === 'childList' && mutation.removedNodes.length > 0) {
          const removedOurElement = Array.from(mutation.removedNodes).some(node => node.id === 'global-token-status');
          if (removedOurElement) {
            this.logger.warn('Global token status element was removed by another system, will reinitialize');
            // Reinitialize after a short delay
            setTimeout(() => {
              if (!document.getElementById('global-token-status')) {
                this.logger.info('Reinitializing global token status element');
                this.waitForTokenStatusElement().then(() => {
                  this.updateGlobalTokenStatus();
                }).catch(error => {
                  this.logger.error('Failed to reinitialize token status element', error);
                });
              }
            }, 100);
          }
        }
      });
    });
 
    // Observe the parent container for changes
    const sidebar = element.parentElement;
    if (sidebar) {
      this.mutationObserver.observe(sidebar, {
        childList: true,
        subtree: true
      });
    }
  }
 
  /**
   * Override conflicting methods in other systems
   */
  overrideConflictingMethods() {
    // Check if UIManager exists and has conflicting methods
    if (window.app && window.app.uiManager) {
      const uiManager = window.app.uiManager;
 
      // Store original methods if they exist
      if (typeof uiManager.updateUniversalTokenStatus === 'function') {
        uiManager._originalUpdateUniversalTokenStatus = uiManager.updateUniversalTokenStatus;
        uiManager.updateUniversalTokenStatus = () => {
          this.logger.debug('UIManager.updateUniversalTokenStatus called - delegating to GlobalTokenManagerSubsystem');
          this.updateGlobalTokenStatus();
        };
      }
      if (typeof uiManager.updateHomeTokenStatus === 'function') {
        uiManager._originalUpdateHomeTokenStatus = uiManager.updateHomeTokenStatus;
        uiManager.updateHomeTokenStatus = () => {
          this.logger.debug('UIManager.updateHomeTokenStatus called - delegating to GlobalTokenManagerSubsystem');
          this.updateGlobalTokenStatus();
        };
      }
      this.logger.debug('Conflicting UIManager methods overridden');
    }
  }
 
  /**
   * Restore original methods in other systems
   */
  restoreOriginalMethods() {
    if (window.app && window.app.uiManager) {
      const uiManager = window.app.uiManager;
 
      // Restore original methods if they were overridden
      if (uiManager._originalUpdateUniversalTokenStatus) {
        uiManager.updateUniversalTokenStatus = uiManager._originalUpdateUniversalTokenStatus;
        delete uiManager._originalUpdateUniversalTokenStatus;
      }
      if (uiManager._originalUpdateHomeTokenStatus) {
        uiManager.updateHomeTokenStatus = uiManager._originalUpdateHomeTokenStatus;
        delete uiManager._originalUpdateHomeTokenStatus;
      }
      this.logger.debug('Original UIManager methods restored');
    }
  }
 
  /**
   * Set up EventBus listeners
   */
  setupEventBusListeners() {
    if (!this.eventBus) {
      return;
    }
 
    // Listen for token refresh events
    this.eventBus.on('token:refreshed', () => {
      this.logger.debug('Token refreshed event received, updating status');
      this.updateGlobalTokenStatus();
    });
 
    // Listen for token error events
    this.eventBus.on('token:error', data => {
      this.logger.debug('Token error event received', data);
      this.updateGlobalTokenStatus();
    });
 
    // Listen for settings changes that might affect token status
    this.eventBus.on('settings:updated', () => {
      this.logger.debug('Settings updated event received, updating token status');
      this.updateGlobalTokenStatus();
    });
    this.logger.debug('EventBus listeners set up for Global Token Manager');
  }
 
  /**
   * Update the global token status display
   */
  updateGlobalTokenStatus() {
    if (this.isDestroyed) {
      return;
    }
    const statusBox = document.getElementById('global-token-status');
    if (!statusBox) {
      // Only log warning once every 30 seconds to reduce spam
      if (!this.lastElementWarning || Date.now() - this.lastElementWarning > 30000) {
        this.logger.debug('Global token status box not found - widget may not be initialized yet');
        this.lastElementWarning = Date.now();
      }
      return;
    }
    const countdown = statusBox.querySelector('.global-token-countdown');
    const icon = statusBox.querySelector('.global-token-icon');
    const text = statusBox.querySelector('.global-token-text');
    const getTokenBtn = document.getElementById('global-get-token');
 
    // If child elements are missing, log debug message but continue with partial updates
    if (!countdown || !icon || !text) {
      // Only log debug message once every 30 seconds to reduce spam
      if (!this.lastChildElementWarning || Date.now() - this.lastChildElementWarning > 30000) {
        this.logger.debug('Some global token status child elements not found, will update what is available', {
          hasCountdown: !!countdown,
          hasIcon: !!icon,
          hasText: !!text,
          statusBoxFound: !!statusBox
        });
        this.lastChildElementWarning = Date.now();
      }
    }
    try {
      // Get current token info (sync version for now to avoid async issues during init)
      const tokenInfo = this.getTokenInfoSync();
      if (tokenInfo.hasToken) {
        // Token exists
        const timeLeft = tokenInfo.timeLeft;
        const formattedTime = this.formatTime(timeLeft);
        if (countdown) countdown.textContent = formattedTime;
        if (timeLeft <= 0) {
          // Token expired
          statusBox.className = 'global-token-status expired';
          if (icon) icon.textContent = '❌';
          if (text) text.textContent = 'Token expired';
          if (getTokenBtn) getTokenBtn.style.display = 'inline-block';
        } else if (timeLeft <= 300) {
          // 5 minutes
          // Token expiring soon
          statusBox.className = 'global-token-status expiring';
          if (icon) icon.textContent = '⚠️';
          if (text) text.textContent = 'Token expiring soon';
          if (getTokenBtn) getTokenBtn.style.display = 'none';
        } else {
          // Token valid
          statusBox.className = 'global-token-status valid';
          if (icon) icon.textContent = '✅';
          if (text) text.textContent = 'Token valid';
          if (getTokenBtn) getTokenBtn.style.display = 'none';
        }
      } else {
        // No token
        statusBox.className = 'global-token-status missing';
        if (icon) icon.textContent = '❌';
        if (text) text.textContent = 'No valid token';
        if (countdown) countdown.textContent = 'No Token';
        if (getTokenBtn) getTokenBtn.style.display = 'inline-block';
      }
    } catch (error) {
      // Reduce error logging frequency to prevent spam
      if (!this.lastErrorWarning || Date.now() - this.lastErrorWarning > 30000) {
        this.logger.debug('Error updating global token status', {
          error: error.message
        });
        this.lastErrorWarning = Date.now();
      }
 
      // Show error state only if elements exist
      if (statusBox) statusBox.className = 'global-token-status error';
      if (icon) icon.textContent = '⚠️';
      if (text) text.textContent = 'Status error';
      if (countdown) countdown.textContent = 'Error';
    }
  }
 
  /**
   * Format time in human-readable format
   */
  formatTime(seconds) {
    if (seconds <= 0) return '00:00';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor(seconds % 3600 / 60);
    const secs = seconds % 60;
    if (hours > 0) {
      return `${hours}h ${minutes}m ${secs}s`;
    } else if (minutes > 0) {
      return `${minutes}m ${secs}s`;
    } else {
      return `${secs}s`;
    }
  }
 
  /**
   * Get current token information (synchronous version for initialization)
   */
  getTokenInfoSync() {
    try {
      // Only check localStorage for sync version to avoid async issues during init
      const token = localStorage.getItem('pingone_worker_token');
      const expiry = localStorage.getItem('pingone_token_expiry');
      if (!token || !expiry) {
        return {
          hasToken: false,
          timeLeft: 0,
          source: 'localStorage'
        };
      }
      const expiryTime = parseInt(expiry);
      const currentTime = Date.now();
      const timeLeft = Math.floor((expiryTime - currentTime) / 1000);
      return {
        hasToken: true,
        timeLeft: Math.max(0, timeLeft),
        source: 'localStorage'
      };
    } catch (error) {
      this.logger.debug('Error getting sync token info', {
        error: error.message
      });
      return {
        hasToken: false,
        timeLeft: 0,
        source: 'error'
      };
    }
  }
 
  /**
   * Get current token information (async version with server fallback)
   */
  async getTokenInfo() {
    try {
      // First try to get token info from server API
      try {
        // Corrected endpoint to align with auth-subsystem API
        const response = await fetch('/api/v1/auth/token');
        if (response.ok) {
          const serverTokenInfo = await response.json();
          // The /token endpoint returns tokenInfo directly
          if (serverTokenInfo.success && serverTokenInfo.tokenInfo) {
            return {
              hasToken: serverTokenInfo.tokenInfo.isValid,
              timeLeft: serverTokenInfo.tokenInfo.timeLeft || 0,
              source: 'server'
            };
          }
        }
      } catch (serverError) {
        this.logger.debug('Could not fetch token info from server, checking localStorage', {
          error: serverError.message
        });
      }
 
      // Fallback to localStorage
      const token = localStorage.getItem('pingone_worker_token');
      const expiry = localStorage.getItem('pingone_token_expiry');
      if (!token || !expiry) {
        return {
          hasToken: false,
          timeLeft: 0,
          source: 'localStorage'
        };
      }
      const expiryTime = parseInt(expiry);
      const currentTime = Date.now();
      const timeLeft = Math.floor((expiryTime - currentTime) / 1000);
      return {
        hasToken: true,
        timeLeft: Math.max(0, timeLeft),
        source: 'localStorage'
      };
    } catch (error) {
      this.logger.error('Error getting token info', {
        error: error.message
      });
      return {
        hasToken: false,
        timeLeft: 0,
        source: 'error'
      };
    }
  }
 
  /**
   * Set up event listeners for global token buttons
   */
  setupGlobalTokenEventListeners() {
    // Refresh button
    const refreshBtn = document.getElementById('global-refresh-token');
    if (refreshBtn) {
      this.refreshBtnHandler = () => {
        this.logger.debug('Refresh token button clicked');
        this.updateGlobalTokenStatus();
      };
      refreshBtn.addEventListener('click', this.refreshBtnHandler);
    }
 
    // Get Token button
    const getTokenBtn = document.getElementById('global-get-token');
    if (getTokenBtn) {
      this.getTokenBtnHandler = () => {
        this.logger.debug('Get token button clicked');
        this.getNewToken();
      };
      getTokenBtn.addEventListener('click', this.getTokenBtnHandler);
    }
    this.logger.debug('Global token event listeners set up');
  }
 
  /**
   * Remove event listeners
   */
  removeEventListeners() {
    const refreshBtn = document.getElementById('global-refresh-token');
    if (refreshBtn && this.refreshBtnHandler) {
      refreshBtn.removeEventListener('click', this.refreshBtnHandler);
    }
    const getTokenBtn = document.getElementById('global-get-token');
    if (getTokenBtn && this.getTokenBtnHandler) {
      getTokenBtn.removeEventListener('click', this.getTokenBtnHandler);
    }
    this.logger.debug('Global token event listeners removed');
  }
 
  /**
   * Start the timer to update token status regularly
   */
  startGlobalTokenTimer() {
    if (this.globalTokenTimer) {
      clearInterval(this.globalTokenTimer);
    }
    this.globalTokenTimer = setInterval(() => {
      if (!this.isDestroyed) {
        this.updateGlobalTokenStatus();
      }
    }, this.updateInterval);
    this.logger.debug('Global token timer started', {
      interval: `${this.updateInterval}ms`
    });
  }
 
  /**
   * Get new token
   */
  async getNewToken() {
    if (this.isDestroyed) {
      return;
    }
    try {
      this.logger.info('Getting new token via global token manager subsystem...');
 
      // Show loading state
      const statusBox = document.getElementById('global-token-status');
      if (statusBox) {
        statusBox.className = 'global-token-status loading';
        const icon = statusBox.querySelector('.global-token-icon');
        const text = statusBox.querySelector('.global-token-text');
        if (icon) icon.textContent = '⏳';
        if (text) text.textContent = 'Getting token...';
      }
 
      // Try to use the app's token refresh functionality
      if (window.app && typeof window.app.getToken === 'function') {
        await window.app.getToken();
        this.logger.info('Token refreshed successfully via app');
      } else {
        // Fallback: try to trigger token refresh through API
        const response = await fetch('/api/auth/refresh-token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        if (response.ok) {
          const result = await response.json();
          this.logger.info('Token refreshed via API', result);
        } else {
          throw new Error(`API request failed: ${response.statusText}`);
        }
      }
 
      // Update status after token refresh
      this.updateGlobalTokenStatus();
 
      // Emit token refresh event
      if (this.eventBus) {
        this.eventBus.emit('globalTokenManager:tokenRefreshed');
      }
    } catch (error) {
      this.logger.error('Error getting new token', {
        error: error.message
      });
 
      // Show error state
      const statusBox = document.getElementById('global-token-status');
      if (statusBox) {
        statusBox.className = 'global-token-status error';
        const icon = statusBox.querySelector('.global-token-icon');
        const text = statusBox.querySelector('.global-token-text');
        if (icon) icon.textContent = '❌';
        if (text) text.textContent = 'Token error';
      }
    }
  }
  formatTime(seconds) {
    if (seconds <= 0) return '00:00';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor(seconds % 3600 / 60);
    const secs = seconds % 60;
    if (hours > 0) {
      return `${hours}h ${minutes}m ${secs}s`;
    } else if (minutes > 0) {
      return `${minutes}m ${secs}s`;
    } else {
      return `${secs}s`;
    }
  }
 
  /**
   * Get current token information
   */
  async getTokenInfo() {
    try {
      // First try to get token info from server API
      try {
        const response = await fetch('/api/token/status');
        if (response.ok) {
          const serverTokenInfo = await response.json();
          if (serverTokenInfo.hasToken) {
            return {
              hasToken: true,
              timeLeft: serverTokenInfo.timeLeft || 0,
              source: 'server'
            };
          }
        }
      } catch (serverError) {
        this.logger.debug('Could not fetch token info from server, checking localStorage', {
          error: serverError.message
        });
      }
 
      // Fallback to localStorage
      const token = localStorage.getItem('pingone_worker_token');
      const expiry = localStorage.getItem('pingone_token_expiry');
      if (!token || !expiry) {
        return {
          hasToken: false,
          timeLeft: 0,
          source: 'localStorage'
        };
      }
      const expiryTime = parseInt(expiry);
      const currentTime = Date.now();
      const timeLeft = Math.floor((expiryTime - currentTime) / 1000);
      return {
        hasToken: true,
        timeLeft: Math.max(0, timeLeft),
        source: 'localStorage'
      };
    } catch (error) {
      this.logger.error('Error getting token info', {
        error: error.message
      });
      return {
        hasToken: false,
        timeLeft: 0,
        source: 'error'
      };
    }
  }
 
  /**
   * Set up event listeners for global token buttons
   */
  setupGlobalTokenEventListeners() {
    // Refresh button
    const refreshBtn = document.getElementById('global-refresh-token');
    if (refreshBtn) {
      this.refreshBtnHandler = () => {
        this.logger.debug('Refresh token button clicked');
        this.updateGlobalTokenStatus();
      };
      refreshBtn.addEventListener('click', this.refreshBtnHandler);
    }
 
    // Get Token button
    const getTokenBtn = document.getElementById('global-get-token');
    if (getTokenBtn) {
      this.getTokenBtnHandler = () => {
        this.logger.debug('Get token button clicked');
        this.getNewToken();
      };
      getTokenBtn.addEventListener('click', this.getTokenBtnHandler);
    }
    this.logger.debug('Global token event listeners set up');
  }
 
  /**
   * Remove event listeners
   */
  removeEventListeners() {
    const refreshBtn = document.getElementById('global-refresh-token');
    if (refreshBtn && this.refreshBtnHandler) {
      refreshBtn.removeEventListener('click', this.refreshBtnHandler);
    }
    const getTokenBtn = document.getElementById('global-get-token');
    if (getTokenBtn && this.getTokenBtnHandler) {
      getTokenBtn.removeEventListener('click', this.getTokenBtnHandler);
    }
    this.logger.debug('Global token event listeners removed');
  }
 
  /**
   * Start the timer to update token status regularly
   */
  startGlobalTokenTimer() {
    if (this.globalTokenTimer) {
      clearInterval(this.globalTokenTimer);
    }
    this.globalTokenTimer = setInterval(() => {
      if (!this.isDestroyed) {
        this.updateGlobalTokenStatus();
      }
    }, this.updateInterval);
    this.logger.debug('Global token timer started', {
      interval: `${this.updateInterval}ms`
    });
  }
 
  /**
   * Get new token
   */
  async getNewToken() {
    if (this.isDestroyed) {
      return;
    }
    try {
      this.logger.info('Getting new token via global token manager subsystem...');
 
      // Show loading state
      const statusBox = document.getElementById('global-token-status');
      if (statusBox) {
        statusBox.className = 'global-token-status loading';
        const icon = statusBox.querySelector('.global-token-icon');
        const text = statusBox.querySelector('.global-token-text');
        if (icon) icon.textContent = '⏳';
        if (text) text.textContent = 'Getting token...';
      }
 
      // Try to use the app's token refresh functionality
      if (window.app && typeof window.app.getToken === 'function') {
        await window.app.getToken();
        this.logger.info('Token refreshed successfully via app');
      } else {
        // Fallback: try to trigger token refresh through API
        const response = await fetch('/api/auth/refresh-token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        if (response.ok) {
          const result = await response.json();
          this.logger.info('Token refreshed via API', result);
        } else {
          throw new Error(`API request failed: ${response.statusText}`);
        }
      }
 
      // Update status after token refresh
      this.updateGlobalTokenStatus();
 
      // Emit token refresh event
      if (this.eventBus) {
        this.eventBus.emit('globalTokenManager:tokenRefreshed');
      }
    } catch (error) {
      this.logger.error('Error getting new token', {
        error: error.message
      });
 
      // Show error state
      const statusBox = document.getElementById('global-token-status');
      if (statusBox) {
        statusBox.className = 'global-token-status error';
        const icon = statusBox.querySelector('.global-token-icon');
        const text = statusBox.querySelector('.global-token-text');
        if (icon) icon.textContent = '❌';
        if (text) text.textContent = 'Token error';
      }
    }
  }
 
  /**
   * Get subsystem status for health checks
   */
  getStatus() {
    return {
      name: 'GlobalTokenManagerSubsystem',
      initialized: this.isInitialized,
      destroyed: this.isDestroyed,
      timerActive: !!this.globalTokenTimer,
      updateInterval: this.updateInterval
    };
  }
}
exports.GlobalTokenManagerSubsystem = GlobalTokenManagerSubsystem;
var _default = exports.default = GlobalTokenManagerSubsystem;
 
},{}],91:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ImportSubsystem = void 0;
/**
 * Import Management Subsystem
 * 
 * Handles all user import operations with proper separation of concerns.
 * Manages file validation, progress tracking, real-time updates, and error handling.
 */
 
class ImportSubsystem {
  constructor(logger, uiManager, localClient, settingsManager, eventBus, populationService) {
    let authManagementSubsystem = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null;
    this.logger = logger;
    this.uiManager = uiManager;
    this.localClient = localClient;
    this.settingsManager = settingsManager;
    this.eventBus = eventBus;
    this.populationService = populationService;
    this.authManagementSubsystem = authManagementSubsystem;
 
    // Import state management
    this.isImporting = false;
    this.socket = null;
    this.selectedPopulationId = null;
    this.selectedPopulationName = null;
    this.fallbackPolling = null;
    this.selectedFile = null; // Tracks the selected file for import
 
    // Initialize message formatter with a fallback
    this.messageFormatter = window.messageFormatter || {
      formatMessage: (type, message) => `[${type.toUpperCase()}] ${message}`
    };
    this.logger.info('Import Subsystem initialized');
 
    // Set up event listeners for cross-subsystem communication
    this.setupCrossSubsystemEvents();
  }
 
  /**
   * Initialize the import subsystem
   */
  async init() {
    (this.logger?.debug || window.logger?.debug || console.log)('🚀 [DEBUG] ImportSubsystem: init() method called');
    try {
      (this.logger?.debug || window.logger?.debug || console.log)('🔧 [DEBUG] ImportSubsystem: Setting up event listeners');
      this.setupEventListeners();
      (this.logger?.debug || window.logger?.debug || console.log)('📋 [DEBUG] ImportSubsystem: About to refresh population dropdown');
      // Initialize population dropdown
      this.refreshPopulationDropdown();
      (this.logger?.debug || window.logger?.debug || console.log)('🔘 [DEBUG] ImportSubsystem: Setting initial button state');
      // Set initial button state (should be disabled until form is complete)
      this.validateAndUpdateButtonState();
      (this.logger?.debug || window.logger?.debug || console.log)('✅ [DEBUG] ImportSubsystem: Init completed successfully');
      (this.logger?.info || window.logger?.info || console.log)('Import Subsystem initialized successfully');
    } catch (error) {
      (this.logger?.error || window.logger?.error || console.error)('❌ [DEBUG] ImportSubsystem: Init failed with error:', error);
      (this.logger?.error || window.logger?.error || console.error)('Failed to initialize Import Subsystem', error);
      throw error;
    }
  }
 
  /**
   * Set up event listeners for import-related elements
   */
  setupEventListeners() {
    // Initialize utilities for safe DOM operations
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        START_IMPORT_BTN: 'start-import',
        CSV_FILE_INPUT: 'csv-file',
        IMPORT_POPULATION_SELECT: 'import-population-select'
      }
    };
 
    // Import button (correct ID is 'start-import') with Safe DOM
    const importBtn = safeDOM.selectById(UI_CONFIG.SELECTORS.START_IMPORT_BTN);
    if (importBtn) {
      safeDOM.addEventListener(importBtn, 'click', errorHandler.wrapAsyncEventHandler(async e => {
        e.preventDefault();
        await this.startImport();
      }, 'Import button click handler'));
    }
 
    // CSV file input with Safe DOM
    const csvFileInput = safeDOM.selectById(UI_CONFIG.SELECTORS.CSV_FILE_INPUT);
    if (csvFileInput) {
      safeDOM.addEventListener(csvFileInput, 'change', errorHandler.wrapAsyncEventHandler(async e => {
        const file = e.target.files[0];
        if (file) {
          this.selectedFile = file; // Update the selected file
          await this.handleFileSelect(file);
          this.validateAndUpdateButtonState();
        }
      }, 'CSV file input change handler'));
    }
 
    // Population dropdown change with Safe DOM
    const populationSelect = safeDOM.selectById(UI_CONFIG.SELECTORS.IMPORT_POPULATION_SELECT);
    if (populationSelect) {
      safeDOM.addEventListener(populationSelect, 'change', errorHandler.wrapEventHandler(e => {
        this.handlePopulationChange(e.target.value, e.target.selectedOptions[0]?.text);
        this.validateAndUpdateButtonState();
      }, 'Population dropdown change handler'));
    }
 
    // Drag & Drop functionality
    this.setupDragAndDropListeners();
  }
 
  /**
   * Set up drag and drop event listeners for CSV file upload
   */
  setupDragAndDropListeners() {
    const dropArea = document.getElementById('import-drop-zone');
    const fileInput = document.getElementById('csv-file');
    if (!dropArea) {
      this.logger.warn('Import drop zone not found in DOM');
      return;
    }
 
    // Prevent default drag behaviors
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
      dropArea.addEventListener(eventName, e => {
        e.preventDefault();
        e.stopPropagation();
      }, false);
    });
 
    // Highlight drop area when item is dragged over it
    ['dragenter', 'dragover'].forEach(eventName => {
      dropArea.addEventListener(eventName, () => {
        dropArea.classList.add('drag-over');
      }, false);
    });
    ['dragleave', 'drop'].forEach(eventName => {
      dropArea.addEventListener(eventName, () => {
        dropArea.classList.remove('drag-over');
      }, false);
    });
 
    // Handle dropped files
    dropArea.addEventListener('drop', async e => {
      const dt = e.dataTransfer;
      const files = dt.files;
      if (files.length > 0) {
        const file = files[0];
        this.selectedFile = file; // Update the selected file
 
        // Update the file input to reflect the dropped file
        if (fileInput) {
          // Create a new FileList-like object
          const dataTransfer = new DataTransfer();
          dataTransfer.items.add(file);
          fileInput.files = dataTransfer.files;
        }
        await this.handleFileSelect(file);
        this.validateAndUpdateButtonState();
      }
    }, false);
 
    // Handle click to browse files
    dropArea.addEventListener('click', () => {
      if (fileInput) {
        fileInput.click();
      }
    });
    this.logger.info('Drag and drop listeners set up successfully');
  }
 
  /**
   * Start the import process
   */
  async startImport() {
    this.logger.info('🚀 [DEBUG] ImportSubsystem: Start import button clicked');
    if (this.isImporting) {
      this.logger.warn('🚀 [DEBUG] ImportSubsystem: Import already in progress');
      this.uiManager.showNotification('An import is already in progress. Please wait for it to complete.', {
        type: 'warning',
        duration: 5000,
        title: 'Import In Progress'
      });
      return;
    }
    try {
      this.isImporting = true;
      this.logger.info('🚀 [DEBUG] ImportSubsystem: Starting import process');
 
      // Validate prerequisites
      this.logger.debug('🚀 [DEBUG] ImportSubsystem: Validating prerequisites...');
      if (!(await this.validateImportPrerequisites())) {
        this.logger.warn('🚀 [DEBUG] ImportSubsystem: Prerequisites validation failed, aborting import');
        return;
      }
      this.logger.info('🚀 [DEBUG] ImportSubsystem: Prerequisites validated, proceeding with import');
 
      // Get population selection
      this.getPopulationSelection();
 
      // Show progress UI
      this.logger.debug('🚀 [DEBUG] ImportSubsystem: Showing progress UI');
      this.uiManager.showProgress();
 
      // Start real-time connection
      const sessionId = this.generateSessionId();
      this.logger.debug('🚀 [DEBUG] ImportSubsystem: Establishing real-time connection with session:', sessionId);
      await this.establishRealTimeConnection(sessionId);
 
      // Begin import process
      this.logger.debug('🚀 [DEBUG] ImportSubsystem: Executing import with session:', sessionId);
      await this.executeImport(sessionId);
    } catch (error) {
      this.logger.error('🚀 [DEBUG] ImportSubsystem: Import process failed', error);
      this.uiManager.showError('Import Failed', error.message || 'An unexpected error occurred during the import process.');
    } finally {
      this.isImporting = false;
      this.logger.debug('🚀 [DEBUG] ImportSubsystem: Import process completed, resetting isImporting flag');
    }
  }
 
  /**
   * Validate import prerequisites
   */
  async validateImportPrerequisites() {
    this.logger.debug('🔍 [DEBUG] ImportSubsystem: Validating import prerequisites');
 
    // Check for valid token
    const hasValidToken = await this.checkTokenStatus();
    if (!hasValidToken) {
      this.logger.warn('🔍 [DEBUG] ImportSubsystem: Token validation failed');
      // Show user-friendly authentication modal with "Go to Settings" button
      this.showAuthenticationModal('Import');
      return false;
    }
 
    // Check file selection using the internal selectedFile property
    if (!this.selectedFile) {
      this.logger.warn('🔍 [DEBUG] ImportSubsystem: No file selected (selectedFile is null)');
      this.uiManager.showError('No File Selected', 'Please select a CSV file to import.');
      return false;
    }
 
    // Check population selection
    const populationSelect = document.getElementById('import-population-select');
    if (!populationSelect || !populationSelect.value || populationSelect.value === '') {
      this.logger.warn('🔍 [DEBUG] ImportSubsystem: No population selected');
      this.uiManager.showError('No Population Selected', 'Please select a population for the import.');
      return false;
    }
    this.logger.info('✅ [DEBUG] ImportSubsystem: All prerequisites validated successfully', {
      hasFile: !!this.selectedFile,
      fileName: this.selectedFile?.name,
      hasPopulation: !!populationSelect?.value,
      populationId: populationSelect?.value
    });
    return true;
  }
 
  /**
   * Get current population selection
   */
  getPopulationSelection() {
    const popSelect = document.getElementById('import-population-select');
    this.selectedPopulationId = popSelect?.value || '';
    if (popSelect) {
      const selectedOption = popSelect.options[popSelect.selectedIndex];
      this.selectedPopulationName = selectedOption?.text || '';
    }
    this.logger.info('Population selection', {
      id: this.selectedPopulationId,
      name: this.selectedPopulationName
    });
  }
 
  /**
   * Handle progress updates
   */
  handleProgressUpdate(data) {
    if (!data || data.current === undefined || data.total === undefined) {
      this.logger.error('Invalid progress data', data);
      return;
    }
    const percentage = Math.round(data.current / data.total * 100);
 
    // Update progress UI
    this.uiManager.updateProgress(percentage, data.message || `Processing ${data.current} of ${data.total} users...`);
    this.logger.info('Progress update', {
      current: data.current,
      total: data.total,
      percentage
    });
  }
 
  /**
   * Handle import completion
   */
  handleImportCompletion(data) {
    this.logger.info('Import completed', data);
    // TODO: Refactor: Use Notification from UI subsystem instead of alert.
    this.cleanupConnections();
  }
 
  /**
   * Handle import errors
   */
  handleImportError(data) {
    this.logger.error('Import error', data);
    // TODO: Refactor: Use Notification or Modal from UI subsystem instead of alert.
    this.cleanupConnections();
  }
 
  /**
   * Execute the import process
   */
  async executeImport(sessionId) {
    const fileInput = document.getElementById('csv-file');
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);
    formData.append('populationId', this.selectedPopulationId);
    formData.append('sessionId', sessionId);
    try {
      const response = await this.localClient.post('/api/import', formData);
      if (!response.success) {
        throw new Error(response.error || 'Import failed');
      }
      this.logger.info('Import request sent successfully');
    } catch (error) {
      this.logger.error('Import request failed', error);
      throw error;
    }
  }
 
  /**
   * Generate unique session ID
   */
  generateSessionId() {
    return `import_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
 
  /**
   * Check token status
   */
  async checkTokenStatus() {
    try {
      (this.logger?.debug || window.logger?.debug || console.log)('🔍 [DEBUG] ImportSubsystem: checkTokenStatus called');
      (this.logger?.debug || window.logger?.debug || console.log)('🔍 [DEBUG] ImportSubsystem: this.authManagementSubsystem =', this.authManagementSubsystem);
      (this.logger?.debug || window.logger?.debug || console.log)('🔍 [DEBUG] ImportSubsystem: typeof this.authManagementSubsystem =', typeof this.authManagementSubsystem);
      if (!this.authManagementSubsystem) {
        this.logger.warn('AuthManagementSubsystem not available for token check');
        (this.logger?.debug || window.logger?.debug || console.log)('❌ [DEBUG] ImportSubsystem: AuthManagementSubsystem is null/undefined');
        return false;
      }
      (this.logger?.debug || window.logger?.debug || console.log)('✅ [DEBUG] ImportSubsystem: AuthManagementSubsystem is available, calling isTokenValid()');
      const isValid = this.authManagementSubsystem.isTokenValid();
      (this.logger?.debug || window.logger?.debug || console.log)('🔍 [DEBUG] ImportSubsystem: isValid =', isValid);
 
      // Also get authentication status for additional info
      const authStatus = this.authManagementSubsystem.getAuthenticationStatus();
      (this.logger?.debug || window.logger?.debug || console.log)('🔍 [DEBUG] ImportSubsystem: authStatus =', authStatus);
      return isValid;
    } catch (error) {
      this.logger.error('Error checking token status:', error);
      (this.logger?.debug || window.logger?.debug || console.log)('❌ [DEBUG] ImportSubsystem: Error in checkTokenStatus:', error);
      return false;
    }
  }
 
  /**
   * Show authentication modal with "Go to Settings" button
   */
  showAuthenticationModal() {
    let operation = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Import';
    try {
      // Create authentication modal directly to avoid bundling issues
      this.createAuthenticationModal(operation);
    } catch (error) {
      this.logger.error('Error showing authentication modal:', error);
      // Fallback to generic error
      this.uiManager.showError('Authentication Required', `You must have a valid token to start an ${operation.toLowerCase()}. Please go to Settings to configure your credentials.`);
    }
  }
 
  /**
   * Create authentication modal with "Go to Settings" button
   */
  createAuthenticationModal(operation) {
    // Initialize utilities for safe DOM operations
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        TOKEN_ALERT_OVERLAY: '.token-alert-overlay',
        SETTINGS_NAV_ITEM: '[data-view="settings"]'
      },
      CLASSES: {
        TOKEN_ALERT_OVERLAY: 'token-alert-overlay'
      }
    };
 
    // Check if modal already exists using Safe DOM
    const existingModal = safeDOM.select(UI_CONFIG.SELECTORS.TOKEN_ALERT_OVERLAY);
    if (existingModal) {
      existingModal.remove();
    }
 
    // Create modal overlay using Safe DOM
    const overlay = document.createElement('div');
    safeDOM.addClass(overlay, UI_CONFIG.CLASSES.TOKEN_ALERT_OVERLAY);
    overlay.setAttribute('role', 'dialog');
    overlay.setAttribute('aria-modal', 'true');
    overlay.setAttribute('aria-labelledby', 'token-alert-title');
    overlay.setAttribute('aria-describedby', 'token-alert-content');
 
    // Modal content with enhanced styling and action button
    overlay.innerHTML = `
            <div class="token-alert-modal" tabindex="-1">
                <div class="token-alert-header">
                    <h2 id="token-alert-title">
                        <span class="warning-icon" aria-hidden="true">⚠️</span>
                        <span>Authentication Required</span>
                    </h2>
                    <button type="button" class="token-alert-close" id="token-alert-close" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="token-alert-body">
                    <div id="token-alert-content" class="token-alert-content">
                        <div class="token-alert-icon">
                            <span aria-hidden="true">🔐</span>
                        </div>
                        <h3>No Valid Token Available</h3>
                        <p class="token-alert-message">
                            <strong>Authentication is required to continue.</strong>
                            You need valid credentials to perform the "${operation}" operation.
                        </p>
                        <div class="token-status-info">
                            <p><strong>Current Status:</strong> No token available</p>
                        </div>
                        <div class="token-alert-actions">
                            <button type="button" class="btn btn-primary btn-lg" id="token-alert-settings-btn">
                                <span class="btn-icon">⚙️</span>
                                Go to Settings
                            </button>
                            <p class="token-alert-help">
                                Add your PingOne credentials in the Settings page to generate a new token.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    document.body.appendChild(overlay);
 
    // Bind events using Safe DOM
    const settingsBtn = safeDOM.select('#token-alert-settings-btn', overlay);
    const closeBtn = safeDOM.select('#token-alert-close', overlay);
 
    // Settings button - navigate to settings with error handling
    if (settingsBtn) {
      safeDOM.addEventListener(settingsBtn, 'click', errorHandler.wrapEventHandler(() => {
        overlay.remove();
        // Navigate to settings view
        if (window.app && window.app.showView) {
          window.app.showView('settings');
        } else {
          // Fallback: trigger the settings nav item using Safe DOM
          const settingsNavItem = safeDOM.select(UI_CONFIG.SELECTORS.SETTINGS_NAV_ITEM);
          if (settingsNavItem) {
            settingsNavItem.click();
          } else {
            // Final fallback: redirect to home page
            window.location.href = '/';
          }
        }
      }, 'Authentication modal settings button click'));
    }
 
    // Close button - allow manual dismissal
    closeBtn.addEventListener('click', () => {
      overlay.remove();
    });
 
    // Trap focus within modal
    overlay.addEventListener('keydown', e => {
      if (e.key === 'Escape') {
        overlay.remove();
      }
    });
 
    // Show modal with animation
    overlay.style.display = 'flex';
    setTimeout(() => {
      overlay.classList.add('show');
    }, 10);
  }
 
  /**
   * Handle file selection
   */
  async handleFileSelect(file) {
    try {
      this.logger.info('File selected for import', {
        name: file.name,
        size: file.size,
        type: file.type
      });
 
      // Validate file
      if (!this.validateFile(file)) {
        return;
      }
 
      // Show file info
      this.displayFileInfo(file);
    } catch (error) {
      this.logger.error('File selection failed', error);
      this.uiManager.showError('File Selection Error', error.message);
    }
  }
 
  /**
   * Validate form state and update Import button enabled/disabled state
   */
  validateAndUpdateButtonState() {
    // Initialize utilities for safe DOM operations
    const safeDOM = window.safeDOM || new SafeDOM(this.logger);
    const errorHandler = window.errorHandler || new ErrorHandler(this.logger);
    const UI_CONFIG = window.UI_CONFIG || {
      SELECTORS: {
        START_IMPORT_BTN: 'start-import',
        IMPORT_POPULATION_SELECT: 'import-population-select'
      },
      CLASSES: {
        BTN_DISABLED: 'btn-disabled',
        BTN_PRIMARY: 'btn-primary'
      }
    };
 
    // Wrap the entire validation in error handler
    errorHandler.wrapSync(() => {
      const importBtn = safeDOM.selectById(UI_CONFIG.SELECTORS.START_IMPORT_BTN);
      if (!importBtn) {
        this.logger.warn('Import button not found for state validation');
        return;
      }
 
      // Check if file is selected (using internal state for reliability)
      const hasFile = !!this.selectedFile;
 
      // Check if population is selected using Safe DOM
      const populationSelect = safeDOM.selectById(UI_CONFIG.SELECTORS.IMPORT_POPULATION_SELECT);
      const hasPopulation = populationSelect && populationSelect.value && populationSelect.value !== '';
 
      // Enable button only if both file and population are selected
      const shouldEnable = hasFile && hasPopulation;
      importBtn.disabled = !shouldEnable;
      this.logger.debug('Import button state updated', {
        hasFile,
        hasPopulation,
        shouldEnable,
        buttonDisabled: importBtn.disabled
      });
 
      // Update button appearance using Safe DOM
      if (shouldEnable) {
        safeDOM.removeClass(importBtn, UI_CONFIG.CLASSES.BTN_DISABLED);
        safeDOM.addClass(importBtn, UI_CONFIG.CLASSES.BTN_PRIMARY);
      } else {
        safeDOM.addClass(importBtn, UI_CONFIG.CLASSES.BTN_DISABLED);
        safeDOM.removeClass(importBtn, UI_CONFIG.CLASSES.BTN_PRIMARY);
      }
    }, 'Import button state validation')();
  }
 
  /**
   * Validate selected file
   */
  validateFile(file) {
    if (!file.name.toLowerCase().endsWith('.csv')) {
      this.uiManager.showError('Invalid File Type', 'Please select a CSV file');
      return false;
    }
    if (file.size > 10 * 1024 * 1024) {
      // 10MB limit
      this.uiManager.showError('File Too Large', 'File size must be less than 10MB');
      return false;
    }
    return true;
  }
 
  /**
   * Display comprehensive file information with record count and validation
   * CRITICAL: This method provides detailed file information display for CSV import UI
   * DO NOT simplify this method - users need comprehensive file details including record counts
   * Last enhanced: 2025-07-22 - Restored missing file information section functionality
   */
  async displayFileInfo(file) {
    try {
      this.logger.info('Displaying comprehensive file information', {
        fileName: file.name
      });
 
      // Parse CSV to get record count and validation information
      let recordCount = null;
      let csvData = null;
      try {
        // Read and parse the CSV file to get accurate record count
        const fileContent = await this.readFileAsText(file);
        csvData = this.parseCSVContent(fileContent);
        recordCount = csvData ? csvData.length : 0;
        this.logger.debug('CSV parsing completed', {
          recordCount,
          hasData: !!csvData
        });
      } catch (parseError) {
        this.logger.warn('Failed to parse CSV for record count', {
          error: parseError.message
        });
        recordCount = 'Unable to determine';
      }
 
      // Use comprehensive file info display with all details
      this.updateFileInfoDisplay(file, recordCount, csvData);
    } catch (error) {
      this.logger.error('Failed to display file information', {
        error: error.message
      });
 
      // Initialize utilities for safe DOM operations
      const safeDOM = window.safeDOM || new SafeDOM(this.logger);
      const UI_CONFIG = window.UI_CONFIG || {
        SELECTORS: {
          FILE_INFO: 'file-info'
        },
        CLASSES: {
          FILE_INFO_ERROR: 'file-info-error'
        },
        STYLES: {
          ERROR_BACKGROUND: '#f8d7da',
          ERROR_BORDER: '1px solid #f5c6cb',
          ERROR_COLOR: '#721c24'
        }
      };
 
      // Fallback to basic file info display using Safe DOM
      const fileInfoElement = safeDOM.selectById(UI_CONFIG.SELECTORS.FILE_INFO);
      if (fileInfoElement) {
        const errorHTML = `
                    <div class="${UI_CONFIG.CLASSES.FILE_INFO_ERROR}" style="background: ${UI_CONFIG.STYLES.ERROR_BACKGROUND}; border: ${UI_CONFIG.STYLES.ERROR_BORDER}; border-radius: 4px; padding: 12px; color: ${UI_CONFIG.STYLES.ERROR_COLOR};">
                        <strong>⚠️ File Information Error</strong><br>
                        Selected: ${file.name}<br>
                        Size: ${(file.size / 1024).toFixed(2)} KB<br>
                        <em>Unable to display detailed information: ${error.message}</em>
                    </div>
                `;
        safeDOM.setHTML(fileInfoElement, errorHTML);
      }
    }
  }
 
  /**
   * Read file as text for CSV parsing
   * @param {File} file - The file to read
   * @returns {Promise<string>} File content as text
   */
  readFileAsText(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = event => resolve(event.target.result);
      reader.onerror = () => reject(new Error('Failed to read file'));
      reader.readAsText(file);
    });
  }
 
  /**
   * Parse CSV content to extract user records
   * @param {string} content - CSV file content
   * @returns {Array} Parsed CSV records
   */
  parseCSVContent(content) {
    if (!content || typeof content !== 'string') {
      return [];
    }
    try {
      // Simple CSV parsing - split by lines and handle basic CSV format
      const lines = content.split('\n').filter(line => line.trim().length > 0);
      if (lines.length <= 1) {
        return []; // No data rows (only header or empty)
      }
 
      // Return data rows (excluding header)
      return lines.slice(1).map(line => {
        // Basic CSV parsing - split by comma and handle quoted fields
        const fields = [];
        let current = '';
        let inQuotes = false;
        for (let i = 0; i < line.length; i++) {
          const char = line[i];
          if (char === '"') {
            inQuotes = !inQuotes;
          } else if (char === ',' && !inQuotes) {
            fields.push(current.trim());
            current = '';
          } else {
            current += char;
          }
        }
        fields.push(current.trim()); // Add the last field
 
        return fields;
      }).filter(row => row.some(field => field.length > 0)); // Filter out empty rows
    } catch (error) {
      this.logger.error('CSV parsing error', {
        error: error.message
      });
      return [];
    }
  }
 
  /**
   * Update file info display with comprehensive information
   * @param {File} file - The selected file
   * @param {number|string} recordCount - Number of records or error message
   * @param {Array} csvData - Parsed CSV data for validation
   */
  updateFileInfoDisplay(file, recordCount, csvData) {
    const fileInfoElement = document.getElementById('file-info');
    if (!fileInfoElement) {
      this.logger.warn('File info element not found in DOM');
      return;
    }
    const fileSize = this.formatFileSize(file.size);
    const lastModified = new Date(file.lastModified).toLocaleString();
    const fileType = file.type || this.getFileExtension(file.name);
    const fileExtension = this.getFileExtension(file.name);
 
    // Determine if file type is valid for CSV import
    const isCSV = fileExtension === 'csv';
    const isText = fileExtension === 'txt';
    const isValidType = isCSV || isText || fileType === 'text/csv' || fileType === 'text/plain';
 
    // Create record count display
    let recordCountHTML = '';
    if (isValidType && recordCount !== null) {
      if (typeof recordCount === 'number') {
        if (recordCount > 0) {
          recordCountHTML = `
                        <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                            <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">🧾 Records</strong>
                            <span style="color: #0073C8; font-size: 0.8rem; font-weight: bold;">${recordCount}</span>
                        </div>
                    `;
        } else {
          recordCountHTML = `
                        <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                            <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">🧾 Records</strong>
                            <span style="color: #dc3545; font-size: 0.8rem; font-weight: bold;">No user records found</span>
                        </div>
                    `;
        }
      } else {
        recordCountHTML = `
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">🧾 Records</strong>
                        <span style="color: #ffc107; font-size: 0.8rem; font-weight: bold;">${recordCount}</span>
                    </div>
                `;
      }
    }
 
    // Create comprehensive file information display
    const fileInfoHTML = `
            <div class="file-info-details" style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 6px; padding: 12px; margin: 8px 0; box-shadow: 0 1px 4px rgba(0,0,0,0.08);">
                
                <!-- File Name Section -->
                <div class="file-name-section" style="text-align: center; margin-bottom: 12px; padding: 8px; background: #e6f4ff; border-radius: 4px; color: #1a237e; font-weight: bold; font-size: 1.1rem;">
                    <div style="font-size: 1.3rem; font-weight: 600; margin-bottom: 3px; color: #1a237e; word-break: break-word; overflow-wrap: break-word;">
                        <i class="fas fa-file-csv" style="margin-right: 6px; font-size: 1.2rem; color: #1976d2;"></i>
                        ${file.name}
                    </div>
                    <div style="font-size: 0.85rem; opacity: 0.9; font-weight: 500; color: #1976d2;">
                        File Selected Successfully
                    </div>
                </div>
                
                <!-- File Information Grid -->
                <div class="file-info-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; font-size: 0.8em; margin-bottom: 10px;">
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">📊 File Size</strong>
                        <span style="color: #6c757d; font-size: 0.8rem;">${fileSize}</span>
                    </div>
                    
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">📅 Modified</strong>
                        <span style="color: #6c757d; font-size: 0.8rem;">${lastModified}</span>
                    </div>
                    
                    <div class="file-info-item" style="background: white; padding: 8px; border-radius: 4px; border: 1px solid #e9ecef;">
                        <strong style="color: #495057; display: block; margin-bottom: 3px; font-size: 0.85rem;">📄 Type</strong>
                        <span style="color: #6c757d; font-size: 0.8rem;">${fileType || 'CSV'}</span>
                    </div>
                    
                    ${recordCountHTML}
                </div>
                
                <!-- File Status -->
                <div class="file-info-status" style="margin-top: 8px; padding: 8px; border-radius: 4px; background: ${isValidType ? '#d4edda' : '#f8d7da'}; border: 1px solid ${isValidType ? '#c3e6cb' : '#f5c6cb'}; display: flex; align-items: center; gap: 6px;">
                    <i class="fas ${isValidType ? 'fa-check-circle' : 'fa-exclamation-triangle'}" style="color: ${isValidType ? '#155724' : '#721c24'};"></i>
                    <span style="color: ${isValidType ? '#155724' : '#721c24'}; font-size: 0.85rem; font-weight: 500;">
                        ${isValidType ? 'Valid CSV file format' : 'Warning: File type may not be compatible'}
                    </span>
                </div>
                
                ${csvData && csvData.length > 0 ? `
                <div class="file-info-preview" style="margin-top: 8px; padding: 8px; border-radius: 4px; background: #fff3cd; border: 1px solid #ffeaa7;">
                    <strong style="color: #856404; font-size: 0.85rem;">📋 Ready for Import</strong>
                    <div style="color: #856404; font-size: 0.8rem; margin-top: 2px;">
                        File contains ${recordCount} user record${recordCount === 1 ? '' : 's'} ready for processing
                    </div>
                </div>
                ` : ''}
            </div>
        `;
    fileInfoElement.innerHTML = fileInfoHTML;
    this.logger.info('File information display updated successfully', {
      recordCount,
      isValidType
    });
  }
 
  /**
   * Format file size for display
   * @param {number} bytes - File size in bytes
   * @returns {string} Formatted file size
   */
  formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
 
  /**
   * Get file extension from filename
   * @param {string} filename - The filename
   * @returns {string} File extension in lowercase
   */
  getFileExtension(filename) {
    return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2).toLowerCase();
  }
 
  /**
   * Establish real-time connection for import progress tracking
   * CRITICAL: This method was missing and causing UI freeze due to infinite await
   * Last implemented: 2025-07-22 - Fixed UI freeze issue by implementing missing method
   */
  async establishRealTimeConnection(sessionId) {
    try {
      this.logger.debug('🔗 [DEBUG] ImportSubsystem: Establishing real-time connection for session:', sessionId);
 
      // Check if Socket.IO is available
      if (typeof io !== 'undefined' && this.subsystems?.realtimeManager) {
        this.logger.debug('🔗 [DEBUG] ImportSubsystem: Socket.IO available, setting up real-time connection');
 
        // Set up Socket.IO connection through realtime subsystem
        this.socket = this.subsystems.realtimeManager.getConnection();
        if (this.socket) {
          // Set up progress event listeners
          this.socket.on(`import-progress-${sessionId}`, data => {
            this.handleProgressUpdate(data);
          });
          this.socket.on(`import-complete-${sessionId}`, data => {
            this.handleImportCompletion(data);
          });
          this.socket.on(`import-error-${sessionId}`, data => {
            this.handleImportError(data);
          });
          this.logger.info('✅ [DEBUG] ImportSubsystem: Real-time connection established successfully');
        } else {
          this.logger.warn('⚠️ [DEBUG] ImportSubsystem: Socket.IO connection not available, using fallback polling');
          this.setupFallbackPolling(sessionId);
        }
      } else {
        this.logger.warn('⚠️ [DEBUG] ImportSubsystem: Socket.IO not available, using fallback polling');
        this.setupFallbackPolling(sessionId);
      }
 
      // Always resolve immediately to prevent UI freeze
      return Promise.resolve();
    } catch (error) {
      this.logger.error('❌ [DEBUG] ImportSubsystem: Failed to establish real-time connection:', error);
      // Set up fallback polling if real-time connection fails
      this.setupFallbackPolling(sessionId);
      // Always resolve to prevent UI freeze
      return Promise.resolve();
    }
  }
 
  /**
   * Clean up connections and resources
   */
  cleanupConnections() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
    if (this.fallbackPolling) {
      clearInterval(this.fallbackPolling);
      this.fallbackPolling = null;
    }
    this.isImporting = false;
  }
 
  /**
   * Set up fallback polling if Socket.IO fails
   */
  setupFallbackPolling(sessionId) {
    this.fallbackPolling = setInterval(async () => {
      try {
        const response = await this.localClient.get(`/api/import/status/${sessionId}`);
        if (response.data) {
          this.handleProgressUpdate(response.data);
        }
      } catch (error) {
        this.logger.error('Fallback polling failed', error);
      }
    }, 2000);
  }
 
  /**
   * Set up cross-subsystem event listeners
   */
  setupCrossSubsystemEvents() {
    if (!this.eventBus) {
      this.logger.warn('EventBus not available for cross-subsystem events');
      return;
    }
 
    // Listen for token expiration events
    this.eventBus.on('tokenExpired', data => {
      this.logger.warn('Token expired during import operation');
      if (this.isImporting) {
        this.cleanupConnections();
        this.uiManager.showError('Session Expired', 'Your authentication token expired during the import. Please re-authenticate and try again.');
      }
    });
 
    // Listen for token error events
    this.eventBus.on('tokenError', data => {
      this.logger.error('Token error detected', data);
      if (this.isImporting) {
        this.cleanupConnections();
        this.uiManager.showError('Authentication Error', `Authentication failed: ${data.error}`);
      }
    });
 
    // Listen for token refresh events
    this.eventBus.on('tokenRefreshed', data => {
      this.logger.info('Token refreshed successfully');
      // Token refresh is handled automatically, just log for now
    });
 
    // Listen for population change events
    this.eventBus.on('populationsChanged', data => {
      this.logger.info('Populations changed, refreshing import dropdown', {
        count: data.count
      });
      this.refreshPopulationDropdown();
    });
    this.logger.debug('Cross-subsystem event listeners set up for ImportSubsystem');
  }
 
  /**
   * Handle population selection change
   */
  handlePopulationChange(populationId, populationName) {
    this.logger.info('🔄 [DEBUG] ImportSubsystem: Population changed', {
      populationId,
      populationName
    });
 
    // Update population name display with better visual distinction
    const populationNameDisplay = document.querySelector('.population-name-text');
    if (populationNameDisplay) {
      if (populationId && populationName) {
        populationNameDisplay.innerHTML = `<span class="population-label">Population:</span> <span class="population-value">${populationName}</span>`;
        this.logger.debug('Updated population name display', {
          populationName
        });
      } else {
        populationNameDisplay.innerHTML = `<span class="population-label">Population:</span> <span class="population-placeholder">Select a population</span>`;
      }
    }
 
    // Update API URL display
    const apiUrlDisplay = document.querySelector('.api-url-text');
    if (apiUrlDisplay) {
      if (populationId) {
        // Construct the API URL for the selected population
        const apiUrl = `/api/populations/${populationId}/users`;
        apiUrlDisplay.textContent = apiUrl;
        this.logger.debug('Updated API URL display', {
          apiUrl
        });
      } else {
        apiUrlDisplay.textContent = 'Select a population to see the API URL';
      }
    }
 
    // Store the selected population for import operations
    this.selectedPopulationId = populationId;
    this.selectedPopulationName = populationName;
 
    // Emit event for other subsystems
    if (this.eventBus) {
      this.eventBus.emit('importPopulationChanged', {
        populationId,
        populationName
      });
    }
  }
 
  /**
   * Refresh the population dropdown for import
   */
  refreshPopulationDropdown() {
    this.logger.info('🔍 [DEBUG] ImportSubsystem: refreshPopulationDropdown called');
 
    // Use PopulationService directly instead of going through app
    if (this.populationService) {
      this.logger.info('🔍 [DEBUG] ImportSubsystem: PopulationService available, calling populateDropdown');
      this.populationService.populateDropdown('import-population-select', {
        includeEmpty: true,
        emptyText: 'Select a population'
      }).then(() => {
        this.logger.info('✅ [DEBUG] ImportSubsystem: Import population dropdown refreshed successfully');
      }).catch(error => {
        this.logger.error('❌ [DEBUG] ImportSubsystem: Failed to refresh import population dropdown', error);
        this.uiManager.showError('Population Refresh Failed', 'Failed to refresh population dropdown.');
      });
    } else {
      this.logger.error('❌ [DEBUG] ImportSubsystem: PopulationService not available for dropdown refresh', {
        populationServiceType: typeof this.populationService,
        populationServiceExists: !!this.populationService
      });
    }
  }
}
exports.ImportSubsystem = ImportSubsystem;
 
},{}],92:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.NavigationSubsystem = void 0;
var _browserLoggingService = require("../utils/browser-logging-service.js");
/**
 * Navigation Subsystem
 * 
 * Manages all navigation, routing, and view switching functionality.
 * Extracted from app.js to provide centralized navigation control.
 * 
 * Features:
 * - View switching and routing
 * - Navigation state management
 * - URL handling and deep linking
 * - View-specific initialization
 * - Navigation history tracking
 */
 
class NavigationSubsystem {
  constructor(logger, uiManager, settingsManager) {
    this.logger = logger || (0, _browserLoggingService.createLogger)({
      serviceName: 'navigation-subsystem',
      environment: 'development'
    });
    this.uiManager = uiManager;
    this.settingsManager = settingsManager;
 
    // Navigation state
    this.currentView = 'home'; // Default view
    this.previousView = null;
    this.navigationHistory = [];
    this.viewInitializers = new Map();
    this.viewCleanupHandlers = new Map();
 
    // Navigation elements
    this.navItems = null;
    this.viewContainers = null;
    this.logger.info('Navigation subsystem initialized');
  }
 
  /**
   * Initialize the navigation subsystem
   */
  async init() {
    try {
      this.logger.info('Initializing navigation subsystem...');
 
      // Find navigation elements
      this.navItems = document.querySelectorAll('[data-view]');
      this.viewContainers = document.querySelectorAll('.view-container, [id$="-view"]');
      this.logger.info('Navigation elements found', {
        navItems: this.navItems.length,
        viewContainers: this.viewContainers.length
      });
 
      // Set up navigation event listeners
      this.setupNavigationListeners();
 
      // Register default view initializers
      this.registerDefaultViewInitializers();
 
      // Initialize current view
      await this.showView(this.currentView);
      this.logger.info('Navigation subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize navigation subsystem', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Set up navigation event listeners
   */
  setupNavigationListeners() {
    this.navItems.forEach(item => {
      item.addEventListener('click', async e => {
        e.preventDefault();
        const view = item.getAttribute('data-view');
        this.logger.debug('Navigation item clicked', {
          view
        });
        if (view && view !== this.currentView) {
          await this.navigateToView(view);
        }
      });
    });
 
    // Handle browser back/forward buttons
    window.addEventListener('popstate', e => {
      if (e.state && e.state.view) {
        this.showView(e.state.view, false); // Don't push to history
      }
    });
    this.logger.debug('Navigation listeners set up');
  }
 
  /**
   * Navigate to a specific view
   * @param {string} view - The view to navigate to
   * @param {Object} options - Navigation options
   */
  async navigateToView(view) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    try {
      this.logger.info('Navigating to view', {
        from: this.currentView,
        to: view
      });
 
      // Validate view exists
      if (!this.isValidView(view)) {
        this.logger.warn('Invalid view requested', {
          view
        });
        return false;
      }
 
      // Check if navigation is allowed
      if (options.force !== true && !(await this.canNavigateFrom(this.currentView))) {
        this.logger.info('Navigation blocked by current view', {
          currentView: this.currentView
        });
        return false;
      }
 
      // Show the view
      const success = await this.showView(view, options.pushToHistory !== false);
      if (success) {
        this.logger.info('Navigation completed successfully', {
          view
        });
      }
      return success;
    } catch (error) {
      this.logger.error('Navigation failed', {
        view,
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Show a specific view
   * @param {string} view - The view to show
   * @param {boolean} pushToHistory - Whether to push to browser history
   */
  async showView(view) {
    let pushToHistory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    try {
      this.logger.debug('Showing view', {
        view,
        pushToHistory
      });
 
      // Store previous view
      this.previousView = this.currentView;
 
      // Run cleanup for previous view
      if (this.previousView && this.viewCleanupHandlers.has(this.previousView)) {
        try {
          await this.viewCleanupHandlers.get(this.previousView)();
          this.logger.debug('View cleanup completed', {
            view: this.previousView
          });
        } catch (error) {
          this.logger.warn('View cleanup failed', {
            view: this.previousView,
            error: error.message
          });
        }
      }
 
      // Hide all views
      this.hideAllViews();
 
      // Show target view
      const viewElement = document.getElementById(`${view}-view`);
      if (viewElement) {
        viewElement.style.display = 'block';
        viewElement.classList.add('active');
      } else {
        this.logger.warn('View element not found', {
          view
        });
        return false;
      }
 
      // Update navigation state
      this.updateNavigationState(view);
 
      // Run view initializer
      if (this.viewInitializers.has(view)) {
        try {
          await this.viewInitializers.get(view)();
          this.logger.debug('View initializer completed', {
            view
          });
        } catch (error) {
          this.logger.warn('View initializer failed', {
            view,
            error: error.message
          });
        }
      }
 
      // Update browser history
      if (pushToHistory && window.history) {
        const url = new URL(window.location);
        url.searchParams.set('view', view);
        window.history.pushState({
          view
        }, '', url);
      }
 
      // Update current view
      this.currentView = view;
 
      // Add to navigation history
      this.navigationHistory.push({
        view,
        timestamp: Date.now(),
        from: this.previousView
      });
 
      // Limit history size
      if (this.navigationHistory.length > 50) {
        this.navigationHistory = this.navigationHistory.slice(-50);
      }
      this.logger.info('View shown successfully', {
        view
      });
      return true;
    } catch (error) {
      this.logger.error('Failed to show view', {
        view,
        error: error.message
      });
      return false;
    }
  }
 
  /**
   * Hide all views
   */
  hideAllViews() {
    this.viewContainers.forEach(container => {
      container.style.display = 'none';
      container.classList.remove('active');
    });
    this.logger.debug('All views hidden');
  }
 
  /**
   * Update navigation state (active nav items, etc.)
   * @param {string} view - The active view
   */
  updateNavigationState(view) {
    // Update navigation items
    this.navItems.forEach(item => {
      item.classList.remove('active');
      if (item.getAttribute('data-view') === view) {
        item.classList.add('active');
      }
    });
 
    // Update page title if needed
    this.updatePageTitle(view);
    this.logger.debug('Navigation state updated', {
      view
    });
  }
 
  /**
   * Update page title based on current view
   * @param {string} view - The current view
   */
  updatePageTitle(view) {
    const titles = {
      'import': 'Import Users',
      'export': 'Export Users',
      'modify': 'Modify Users',
      'delete-csv': 'Delete Users',
      'settings': 'Settings',
      'logs': 'Logs',
      'history': 'History'
    };
    const baseTitle = 'PingOne User Import v6.5.1.1';
    const viewTitle = titles[view];
    if (viewTitle) {
      document.title = `${viewTitle} - ${baseTitle}`;
    } else {
      document.title = baseTitle;
    }
  }
 
  /**
   * Register a view initializer
   * @param {string} view - The view name
   * @param {Function} initializer - The initializer function
   */
  registerViewInitializer(view, initializer) {
    this.viewInitializers.set(view, initializer);
    this.logger.debug('View initializer registered', {
      view
    });
  }
 
  /**
   * Register a view cleanup handler
   * @param {string} view - The view name
   * @param {Function} cleanup - The cleanup function
   */
  registerViewCleanup(view, cleanup) {
    this.viewCleanupHandlers.set(view, cleanup);
    this.logger.debug('View cleanup handler registered', {
      view
    });
  }
 
  /**
   * Register default view initializers
   */
  registerDefaultViewInitializers() {
    // Import view initializer
    this.registerViewInitializer('import', async () => {
      if (typeof window.app?.loadPopulations === 'function') {
        await window.app.loadPopulations('import-population-select');
      }
    });
 
    // Export view initializer
    this.registerViewInitializer('export', async () => {
      if (window.exportManager && typeof window.exportManager.loadPopulations === 'function') {
        await window.exportManager.loadPopulations();
      }
    });
 
    // Delete view initializer
    this.registerViewInitializer('delete-csv', async () => {
      if (window.deleteManager && typeof window.deleteManager.loadPopulations === 'function') {
        await window.deleteManager.loadPopulations();
      }
    });
 
    // Modify view initializer
    this.registerViewInitializer('modify', async () => {
      if (typeof window.app?.loadPopulations === 'function') {
        await window.app.loadPopulations('modify-population-select');
      }
    });
 
    // Logs/History view initializer
    this.registerViewInitializer('logs', async () => {
      if (window.logManager && typeof window.logManager.loadLogs === 'function') {
        window.logManager.loadLogs();
      }
    });
    this.registerViewInitializer('history', async () => {
      if (window.logManager && typeof window.logManager.loadLogs === 'function') {
        window.logManager.loadLogs();
      }
    });
    this.logger.debug('Default view initializers registered');
  }
 
  /**
   * Check if a view is valid
   * @param {string} view - The view to validate
   * @returns {boolean} - Whether the view is valid
   */
  isValidView(view) {
    const validViews = ['home', 'import', 'export', 'modify', 'delete-csv', 'settings', 'logs', 'history', 'analytics'];
    return validViews.includes(view);
  }
 
  /**
   * Check if navigation is allowed from current view
   * @param {string} fromView - The view to navigate from
   * @returns {Promise<boolean>} - Whether navigation is allowed
   */
  async canNavigateFrom(fromView) {
    // Check for unsaved changes, running operations, etc.
 
    // Check if import is running
    if (fromView === 'import' && window.app?.isImportRunning) {
      const confirmed = confirm('Import is currently running. Are you sure you want to leave this page?');
      return confirmed;
    }
 
    // Check if export is running
    if (fromView === 'export' && window.exportManager?.isExportRunning) {
      const confirmed = confirm('Export is currently running. Are you sure you want to leave this page?');
      return confirmed;
    }
 
    // Check if delete is running
    if (fromView === 'delete-csv' && window.deleteManager?.isDeleteRunning) {
      const confirmed = confirm('Delete operation is currently running. Are you sure you want to leave this page?');
      return confirmed;
    }
 
    // Check for unsaved settings
    if (fromView === 'settings' && this.settingsManager?.hasUnsavedChanges?.()) {
      const confirmed = confirm('You have unsaved settings. Are you sure you want to leave without saving?');
      return confirmed;
    }
    return true;
  }
 
  /**
   * Get current view
   * @returns {string} - The current view
   */
  getCurrentView() {
    return this.currentView;
  }
 
  /**
   * Get previous view
   * @returns {string|null} - The previous view
   */
  getPreviousView() {
    return this.previousView;
  }
 
  /**
   * Get navigation history
   * @returns {Array} - The navigation history
   */
  getNavigationHistory() {
    return [...this.navigationHistory];
  }
 
  /**
   * Go back to previous view
   */
  async goBack() {
    if (this.previousView) {
      await this.navigateToView(this.previousView);
    } else if (this.navigationHistory.length > 1) {
      const previousEntry = this.navigationHistory[this.navigationHistory.length - 2];
      await this.navigateToView(previousEntry.view);
    }
  }
 
  /**
   * Refresh current view
   */
  async refreshCurrentView() {
    await this.showView(this.currentView, false);
  }
 
  /**
   * Get view statistics
   * @returns {Object} - View usage statistics
   */
  getViewStats() {
    const stats = {};
    this.navigationHistory.forEach(entry => {
      if (!stats[entry.view]) {
        stats[entry.view] = {
          count: 0,
          lastVisited: null
        };
      }
      stats[entry.view].count++;
      stats[entry.view].lastVisited = entry.timestamp;
    });
    return stats;
  }
 
  /**
   * Clean up the navigation subsystem
   */
  cleanup() {
    // Remove event listeners
    this.navItems.forEach(item => {
      item.removeEventListener('click', this.handleNavClick);
    });
    window.removeEventListener('popstate', this.handlePopState);
 
    // Clear state
    this.viewInitializers.clear();
    this.viewCleanupHandlers.clear();
    this.navigationHistory = [];
    this.logger.info('Navigation subsystem cleaned up');
  }
}
exports.NavigationSubsystem = NavigationSubsystem;
 
},{"../utils/browser-logging-service.js":97}],93:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.OperationManagerSubsystem = void 0;
var _browserLoggingService = require("../utils/browser-logging-service.js");
/**
 * Operation Manager Subsystem
 * 
 * Manages all CRUD operations (Import, Export, Delete, Modify) with centralized
 * orchestration, validation, progress tracking, and error handling.
 * 
 * Features:
 * - Unified operation lifecycle management
 * - Operation validation and pre-checks
 * - Progress tracking and status updates
 * - Error handling and recovery
 * - Operation queuing and concurrency control
 * - Operation history and logging
 */
 
class OperationManagerSubsystem {
  constructor(logger, uiManager, settingsManager, apiClient) {
    this.logger = logger || (0, _browserLoggingService.createLogger)({
      serviceName: 'operation-manager-subsystem',
      environment: 'development'
    });
    this.uiManager = uiManager;
    this.settingsManager = settingsManager;
    this.apiClient = apiClient;
 
    // Operation state
    this.currentOperation = null;
    this.operationQueue = [];
    this.operationHistory = [];
    this.isOperationRunning = false;
 
    // Operation types
    this.operationTypes = {
      IMPORT: 'import',
      EXPORT: 'export',
      DELETE: 'delete',
      MODIFY: 'modify'
    };
 
    // Operation validators
    this.validators = new Map();
    this.preChecks = new Map();
    this.postChecks = new Map();
    this.logger.info('Operation Manager subsystem initialized');
  }
 
  /**
   * Initialize the operation manager subsystem
   */
  async init() {
    try {
      this.logger.info('Initializing operation manager subsystem...');
 
      // Register default validators and checks
      this.registerDefaultValidators();
      this.registerDefaultPreChecks();
      this.registerDefaultPostChecks();
      this.logger.info('Operation Manager subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize operation manager subsystem', {
        error: error.message
      });
      throw error;
    }
  }
 
  /**
   * Start an operation
   * @param {string} type - Operation type (import, export, delete, modify)
   * @param {Object} options - Operation options
   * @returns {Promise<Object>} - Operation result
   */
  async startOperation(type) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    try {
      this.logger.info('Starting operation', {
        type,
        options
      });
 
      // Check if operation is already running
      if (this.isOperationRunning) {
        throw new Error('Another operation is already running');
      }
 
      // Validate operation type
      if (!Object.values(this.operationTypes).includes(type)) {
        throw new Error(`Invalid operation type: ${type}`);
      }
 
      // Create operation context
      const operation = {
        id: this.generateOperationId(),
        type,
        options,
        status: 'initializing',
        startTime: Date.now(),
        endTime: null,
        progress: {
          current: 0,
          total: 0,
          percentage: 0,
          message: 'Initializing...'
        },
        result: null,
        error: null
      };
      this.currentOperation = operation;
      this.isOperationRunning = true;
 
      // Run pre-checks
      await this.runPreChecks(operation);
 
      // Validate operation
      await this.validateOperation(operation);
 
      // Execute operation
      const result = await this.executeOperation(operation);
 
      // Run post-checks
      await this.runPostChecks(operation);
 
      // Complete operation
      operation.status = 'completed';
      operation.endTime = Date.now();
      operation.result = result;
      this.logger.info('Operation completed successfully', {
        type,
        duration: operation.endTime - operation.startTime
      });
      return result;
    } catch (error) {
      this.logger.error('Operation failed', {
        type,
        error: error.message
      });
      if (this.currentOperation) {
        this.currentOperation.status = 'failed';
        this.currentOperation.endTime = Date.now();
        this.currentOperation.error = error.message;
      }
      throw error;
    } finally {
      // Clean up
      this.finalizeOperation();
    }
  }
 
  /**
   * Execute the actual operation
   * @param {Object} operation - Operation context
   * @returns {Promise<Object>} - Operation result
   */
  async executeOperation(operation) {
    const {
      type,
      options
    } = operation;
    this.logger.debug('Executing operation', {
      type
    });
    switch (type) {
      case this.operationTypes.IMPORT:
        return await this.executeImport(operation);
      case this.operationTypes.EXPORT:
        return await this.executeExport(operation);
      case this.operationTypes.DELETE:
        return await this.executeDelete(operation);
      case this.operationTypes.MODIFY:
        return await this.executeModify(operation);
      default:
        throw new Error(`Unknown operation type: ${type}`);
    }
  }
 
  /**
   * Execute import operation
   * @param {Object} operation - Operation context
   * @returns {Promise<Object>} - Import result
   */
  async executeImport(operation) {
    const {
      options
    } = operation;
    this.logger.info('Executing import operation', {
      options
    });
 
    // Update progress
    this.updateOperationProgress(operation, 0, 100, 'Starting import...');
 
    // Prepare import data
    const importData = {
      file: options.file,
      populationId: options.populationId,
      populationName: options.populationName,
      skipDuplicates: options.skipDuplicates || false,
      updateExisting: options.updateExisting || false
    };
 
    // Start import via API
    const response = await this.apiClient.post('/api/import', importData);
    if (!response.success) {
      throw new Error(response.error || 'Import failed');
    }
 
    // Track progress via SSE or polling
    await this.trackOperationProgress(operation, response.sessionId);
    return {
      success: true,
      sessionId: response.sessionId,
      message: 'Import completed successfully'
    };
  }
 
  /**
   * Execute export operation
   * @param {Object} operation - Operation context
   * @returns {Promise<Object>} - Export result
   */
  async executeExport(operation) {
    const {
      options
    } = operation;
    this.logger.info('Executing export operation', {
      options
    });
 
    // Update progress
    this.updateOperationProgress(operation, 0, 100, 'Starting export...');
 
    // Prepare export data
    const exportData = {
      populationId: options.populationId,
      populationName: options.populationName,
      includeDisabled: options.includeDisabled || false,
      format: options.format || 'csv'
    };
 
    // Start export via API
    const response = await this.apiClient.post('/api/export', exportData);
    if (!response.success) {
      throw new Error(response.error || 'Export failed');
    }
 
    // Track progress
    await this.trackOperationProgress(operation, response.sessionId);
    return {
      success: true,
      sessionId: response.sessionId,
      downloadUrl: response.downloadUrl,
      message: 'Export completed successfully'
    };
  }
 
  /**
   * Execute delete operation
   * @param {Object} operation - Operation context
   * @returns {Promise<Object>} - Delete result
   */
  async executeDelete(operation) {
    const {
      options
    } = operation;
    this.logger.info('Executing delete operation', {
      options
    });
 
    // Update progress
    this.updateOperationProgress(operation, 0, 100, 'Starting delete...');
 
    // Prepare delete data
    const deleteData = {
      file: options.file,
      populationId: options.populationId,
      populationName: options.populationName,
      confirmDelete: true
    };
 
    // Start delete via API
    const response = await this.apiClient.post('/api/delete', deleteData);
    if (!response.success) {
      throw new Error(response.error || 'Delete failed');
    }
 
    // Track progress
    await this.trackOperationProgress(operation, response.sessionId);
    return {
      success: true,
      sessionId: response.sessionId,
      message: 'Delete completed successfully'
    };
  }
 
  /**
   * Execute modify operation
   * @param {Object} operation - Operation context
   * @returns {Promise<Object>} - Modify result
   */
  async executeModify(operation) {
    const {
      options
    } = operation;
    this.logger.info('Executing modify operation', {
      options
    });
 
    // Update progress
    this.updateOperationProgress(operation, 0, 100, 'Starting modify...');
 
    // Prepare modify data
    const modifyData = {
      file: options.file,
      populationId: options.populationId,
      populationName: options.populationName,
      updateFields: options.updateFields || []
    };
 
    // Start modify via API
    const response = await this.apiClient.post('/api/modify', modifyData);
    if (!response.success) {
      throw new Error(response.error || 'Modify failed');
    }
 
    // Track progress
    await this.trackOperationProgress(operation, response.sessionId);
    return {
      success: true,
      sessionId: response.sessionId,
      message: 'Modify completed successfully'
    };
  }
 
  /**
   * Track operation progress via SSE or polling
   * @param {Object} operation - Operation context
   * @param {string} sessionId - Session ID for tracking
   */
  async trackOperationProgress(operation, sessionId) {
    return new Promise((resolve, reject) => {
      // Try SSE first
      if (typeof EventSource !== 'undefined') {
        this.trackProgressViaSSE(operation, sessionId, resolve, reject);
      } else {
        // Fallback to polling
        this.trackProgressViaPolling(operation, sessionId, resolve, reject);
      }
    });
  }
 
  /**
   * Track progress via Server-Sent Events
   * @param {Object} operation - Operation context
   * @param {string} sessionId - Session ID
   * @param {Function} resolve - Promise resolve function
   * @param {Function} reject - Promise reject function
   */
  trackProgressViaSSE(operation, sessionId, resolve, reject) {
    const eventSource = new EventSource(`/api/progress/${sessionId}`);
    eventSource.onmessage = event => {
      try {
        const data = JSON.parse(event.data);
        this.handleProgressUpdate(operation, data);
        if (data.status === 'completed') {
          eventSource.close();
          resolve(data);
        } else if (data.status === 'failed') {
          eventSource.close();
          reject(new Error(data.error || 'Operation failed'));
        }
      } catch (error) {
        this.logger.error('Error parsing SSE data', {
          error: error.message
        });
      }
    };
    eventSource.onerror = error => {
      this.logger.error('SSE connection error', {
        error
      });
      eventSource.close();
      // Fallback to polling
      this.trackProgressViaPolling(operation, sessionId, resolve, reject);
    };
  }
 
  /**
   * Track progress via polling
   * @param {Object} operation - Operation context
   * @param {string} sessionId - Session ID
   * @param {Function} resolve - Promise resolve function
   * @param {Function} reject - Promise reject function
   */
  async trackProgressViaPolling(operation, sessionId, resolve, reject) {
    const pollInterval = 1000; // 1 second
 
    const poll = async () => {
      try {
        const response = await this.apiClient.get(`/api/progress/${sessionId}`);
        if (response.success) {
          this.handleProgressUpdate(operation, response.data);
          if (response.data.status === 'completed') {
            resolve(response.data);
          } else if (response.data.status === 'failed') {
            reject(new Error(response.data.error || 'Operation failed'));
          } else {
            setTimeout(poll, pollInterval);
          }
        } else {
          reject(new Error(response.error || 'Failed to get progress'));
        }
      } catch (error) {
        reject(error);
      }
    };
    poll();
  }
 
  /**
   * Handle progress update
   * @param {Object} operation - Operation context
   * @param {Object} progressData - Progress data from server
   */
  handleProgressUpdate(operation, progressData) {
    // Update operation progress
    operation.progress = {
      current: progressData.current || 0,
      total: progressData.total || 0,
      percentage: progressData.percentage || 0,
      message: progressData.message || 'Processing...'
    };
 
    // Update UI
    if (this.uiManager) {
      this.uiManager.updateProgress(operation.progress.current, operation.progress.total, operation.progress.message);
    }
    this.logger.debug('Progress updated', {
      type: operation.type,
      progress: operation.progress
    });
  }
 
  /**
   * Update operation progress
   * @param {Object} operation - Operation context
   * @param {number} current - Current progress
   * @param {number} total - Total progress
   * @param {string} message - Progress message
   */
  updateOperationProgress(operation, current, total, message) {
    const percentage = total > 0 ? Math.round(current / total * 100) : 0;
    operation.progress = {
      current,
      total,
      percentage,
      message
    };
 
    // Update UI
    if (this.uiManager) {
      this.uiManager.updateProgress(current, total, message);
    }
    this.logger.debug('Operation progress updated', {
      type: operation.type,
      progress: operation.progress
    });
  }
 
  /**
   * Run pre-checks for operation
   * @param {Object} operation - Operation context
   */
  async runPreChecks(operation) {
    const preCheck = this.preChecks.get(operation.type);
    if (preCheck) {
      this.logger.debug('Running pre-checks', {
        type: operation.type
      });
      await preCheck(operation);
    }
  }
 
  /**
   * Validate operation
   * @param {Object} operation - Operation context
   */
  async validateOperation(operation) {
    const validator = this.validators.get(operation.type);
    if (validator) {
      this.logger.debug('Validating operation', {
        type: operation.type
      });
      await validator(operation);
    }
  }
 
  /**
   * Run post-checks for operation
   * @param {Object} operation - Operation context
   */
  async runPostChecks(operation) {
    const postCheck = this.postChecks.get(operation.type);
    if (postCheck) {
      this.logger.debug('Running post-checks', {
        type: operation.type
      });
      await postCheck(operation);
    }
  }
 
  /**
   * Finalize operation
   */
  finalizeOperation() {
    if (this.currentOperation) {
      // Add to history
      this.operationHistory.push({
        ...this.currentOperation
      });
 
      // Limit history size
      if (this.operationHistory.length > 100) {
        this.operationHistory = this.operationHistory.slice(-100);
      }
 
      // Clear current operation
      this.currentOperation = null;
    }
    this.isOperationRunning = false;
    this.logger.debug('Operation finalized');
  }
 
  /**
   * Register default validators
   */
  registerDefaultValidators() {
    // Import validator
    this.validators.set(this.operationTypes.IMPORT, async operation => {
      const {
        options
      } = operation;
      if (!options.file) {
        throw new Error('No file selected for import');
      }
      if (!options.populationId) {
        throw new Error('No population selected for import');
      }
    });
 
    // Export validator
    this.validators.set(this.operationTypes.EXPORT, async operation => {
      const {
        options
      } = operation;
      if (!options.populationId) {
        throw new Error('No population selected for export');
      }
    });
 
    // Delete validator
    this.validators.set(this.operationTypes.DELETE, async operation => {
      const {
        options
      } = operation;
      if (!options.file) {
        throw new Error('No file selected for delete');
      }
      if (!options.populationId) {
        throw new Error('No population selected for delete');
      }
    });
 
    // Modify validator
    this.validators.set(this.operationTypes.MODIFY, async operation => {
      const {
        options
      } = operation;
      if (!options.file) {
        throw new Error('No file selected for modify');
      }
      if (!options.populationId) {
        throw new Error('No population selected for modify');
      }
    });
  }
 
  /**
   * Register default pre-checks
   */
  registerDefaultPreChecks() {
    // Common pre-check for all operations
    const commonPreCheck = async operation => {
      // Check token validity
      if (window.app && typeof window.app.checkTokenAndRedirect === 'function') {
        const hasValidToken = await window.app.checkTokenAndRedirect(operation.type);
        if (!hasValidToken) {
          throw new Error('Invalid or expired token');
        }
      }
    };
 
    // Register for all operation types
    Object.values(this.operationTypes).forEach(type => {
      this.preChecks.set(type, commonPreCheck);
    });
  }
 
  /**
   * Register default post-checks
   */
  registerDefaultPostChecks() {
    // Common post-check for all operations
    const commonPostCheck = async operation => {
      // Log operation completion
      this.logger.info('Operation completed', {
        type: operation.type,
        duration: operation.endTime - operation.startTime,
        status: operation.status
      });
    };
 
    // Register for all operation types
    Object.values(this.operationTypes).forEach(type => {
      this.postChecks.set(type, commonPostCheck);
    });
  }
 
  /**
   * Generate unique operation ID
   * @returns {string} - Unique operation ID
   */
  generateOperationId() {
    return `op_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
 
  /**
   * Cancel current operation
   */
  async cancelOperation() {
    if (this.currentOperation && this.isOperationRunning) {
      this.logger.info('Cancelling operation', {
        type: this.currentOperation.type
      });
      try {
        // Try to cancel via API
        if (this.currentOperation.sessionId) {
          await this.apiClient.post(`/api/cancel/${this.currentOperation.sessionId}`);
        }
        this.currentOperation.status = 'cancelled';
        this.currentOperation.endTime = Date.now();
        this.logger.info('Operation cancelled successfully');
      } catch (error) {
        this.logger.error('Failed to cancel operation', {
          error: error.message
        });
      } finally {
        this.finalizeOperation();
      }
    }
  }
 
  /**
   * Get current operation status
   * @returns {Object|null} - Current operation or null
   */
  getCurrentOperation() {
    return this.currentOperation ? {
      ...this.currentOperation
    } : null;
  }
 
  /**
   * Get operation history
   * @returns {Array} - Operation history
   */
  getOperationHistory() {
    return [...this.operationHistory];
  }
 
  /**
   * Check if operation is running
   * @returns {boolean} - Whether operation is running
   */
  isRunning() {
    return this.isOperationRunning;
  }
 
  /**
   * Get operation statistics
   * @returns {Object} - Operation statistics
   */
  getOperationStats() {
    const stats = {
      total: this.operationHistory.length,
      byType: {},
      byStatus: {},
      averageDuration: 0
    };
    let totalDuration = 0;
    this.operationHistory.forEach(op => {
      // By type
      if (!stats.byType[op.type]) {
        stats.byType[op.type] = 0;
      }
      stats.byType[op.type]++;
 
      // By status
      if (!stats.byStatus[op.status]) {
        stats.byStatus[op.status] = 0;
      }
      stats.byStatus[op.status]++;
 
      // Duration
      if (op.endTime && op.startTime) {
        totalDuration += op.endTime - op.startTime;
      }
    });
    if (this.operationHistory.length > 0) {
      stats.averageDuration = Math.round(totalDuration / this.operationHistory.length);
    }
    return stats;
  }
}
exports.OperationManagerSubsystem = OperationManagerSubsystem;
 
},{"../utils/browser-logging-service.js":97}],94:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RealtimeCommunicationSubsystem = void 0;
function _interopRequireWildcard(e, t) {
  if ("function" == typeof WeakMap) var r = new WeakMap(),
    n = new WeakMap();
  return (_interopRequireWildcard = function (e, t) {
    if (!t && e && e.__esModule) return e;
    var o,
      i,
      f = {
        __proto__: null,
        default: e
      };
    if (null === e || "object" != typeof e && "function" != typeof e) return f;
    if (o = t ? n : r) {
      if (o.has(e)) return o.get(e);
      o.set(e, f);
    }
    for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]);
    return f;
  })(e, t);
}
/**
 * Real-time Communication Subsystem
 * 
 * Handles all real-time communication including Socket.IO connections,
 * WebSocket fallbacks, and Server-Sent Events for progress updates.
 */
 
class RealtimeCommunicationSubsystem {
  constructor(logger, uiManager) {
    this.logger = logger;
    this.uiManager = uiManager;
 
    // Connection state management
    this.socket = null;
    this.eventSource = null;
    this.fallbackPolling = null;
    this.connectionType = null;
    this.isConnected = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectDelay = 1000;
 
    // Event handlers
    this.eventHandlers = new Map();
    this.logger.info('Real-time Communication Subsystem initialized');
  }
 
  /**
   * Initialize the real-time communication subsystem
   */
  async init() {
    try {
      this.setupConnectionMonitoring();
      this.logger.info('Real-time Communication Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Real-time Communication Subsystem', error);
      throw error;
    }
  }
 
  /**
   * Establish real-time connection with fallback strategy
   */
  async establishConnection(sessionId) {
    let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    const {
      preferredTransport = 'socketio',
      enableFallback = true,
      timeout = 10000
    } = options;
    this.logger.info('Establishing real-time connection', {
      sessionId,
      preferredTransport,
      enableFallback
    });
    try {
      // Try primary transport first
      if (preferredTransport === 'socketio') {
        await this.connectSocketIO(sessionId, timeout);
      } else if (preferredTransport === 'sse') {
        await this.connectSSE(sessionId, timeout);
      } else if (preferredTransport === 'websocket') {
        await this.connectWebSocket(sessionId, timeout);
      }
    } catch (error) {
      this.logger.warn('Primary transport failed', {
        error: error.message
      });
      if (enableFallback) {
        await this.tryFallbackConnections(sessionId);
      } else {
        throw error;
      }
    }
  }
 
  /**
   * Connect using Socket.IO
   */
  async connectSocketIO(sessionId) {
    let timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000;
    return new Promise(async (resolve, reject) => {
      try {
        // Import Socket.IO dynamically
        const {
          io
        } = await Promise.resolve().then(() => _interopRequireWildcard(require('socket.io-client')));
        this.socket = io({
          transports: ['polling'],
          reconnectionAttempts: this.maxReconnectAttempts,
          reconnectionDelay: this.reconnectDelay,
          timeout: timeout,
          forceNew: true,
          autoConnect: true
        });
 
        // Set up connection timeout
        const connectionTimeout = setTimeout(() => {
          reject(new Error('Socket.IO connection timeout'));
        }, timeout);
 
        // Connection success
        this.socket.on('connect', () => {
          clearTimeout(connectionTimeout);
          this.connectionType = 'socketio';
          this.isConnected = true;
          this.reconnectAttempts = 0;
 
          // Set up Socket.IO event handlers
          this.setupSocketIOHandlers();
 
          // Register session
          this.socket.emit('registerSession', sessionId);
          this.logger.info('Socket.IO connected successfully');
          this.uiManager.showSuccess('Real-time connection established (Socket.IO)');
          resolve();
        });
 
        // Connection error
        this.socket.on('connect_error', error => {
          clearTimeout(connectionTimeout);
          this.logger.error('Socket.IO connection error', error);
          reject(error);
        });
 
        // Set up event handlers
        this.setupSocketIOHandlers();
      } catch (error) {
        this.logger.error('Failed to initialize Socket.IO', error);
        reject(error);
      }
    });
  }
 
  /**
   * Connect using Server-Sent Events
   */
  async connectSSE(sessionId) {
    let timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000;
    return new Promise((resolve, reject) => {
      try {
        const sseUrl = `/api/progress/stream/${sessionId}`;
        this.eventSource = new EventSource(sseUrl);
 
        // Set up connection timeout
        const connectionTimeout = setTimeout(() => {
          reject(new Error('SSE connection timeout'));
        }, timeout);
 
        // Connection success
        this.eventSource.onopen = () => {
          clearTimeout(connectionTimeout);
          this.connectionType = 'sse';
          this.isConnected = true;
          this.reconnectAttempts = 0;
          this.logger.info('SSE connected successfully');
          this.uiManager.showSuccess('Real-time connection established (SSE)');
          resolve();
        };
 
        // Connection error
        this.eventSource.onerror = error => {
          clearTimeout(connectionTimeout);
          this.logger.error('SSE connection error', error);
          reject(error);
        };
 
        // Set up event handlers
        this.setupSSEHandlers();
      } catch (error) {
        this.logger.error('Failed to initialize SSE', error);
        reject(error);
      }
    });
  }
 
  /**
   * Connect using WebSocket
   */
  async connectWebSocket(sessionId) {
    let timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000;
    return new Promise((resolve, reject) => {
      try {
        const wsUrl = `ws://${window.location.host}/ws/${sessionId}`;
        this.websocket = new WebSocket(wsUrl);
 
        // Set up connection timeout
        const connectionTimeout = setTimeout(() => {
          reject(new Error('WebSocket connection timeout'));
        }, timeout);
 
        // Connection success
        this.websocket.onopen = () => {
          clearTimeout(connectionTimeout);
          this.connectionType = 'websocket';
          this.isConnected = true;
          this.reconnectAttempts = 0;
          this.logger.info('WebSocket connected successfully');
          this.uiManager.showSuccess('Real-time connection established (WebSocket)');
          resolve();
        };
 
        // Connection error
        this.websocket.onerror = error => {
          clearTimeout(connectionTimeout);
          this.logger.error('WebSocket connection error', error);
          reject(error);
        };
 
        // Set up event handlers
        this.setupWebSocketHandlers();
      } catch (error) {
        this.logger.error('Failed to initialize WebSocket', error);
        reject(error);
      }
    });
  }
 
  /**
   * Try fallback connections in order
   */
  async tryFallbackConnections(sessionId) {
    const fallbackOrder = ['sse', 'websocket', 'polling'];
    for (const transport of fallbackOrder) {
      if (transport === this.connectionType) {
        continue; // Skip the one that already failed
      }
      try {
        this.logger.info(`Trying fallback transport: ${transport}`);
        if (transport === 'sse') {
          await this.connectSSE(sessionId);
        } else if (transport === 'websocket') {
          await this.connectWebSocket(sessionId);
        } else if (transport === 'polling') {
          await this.setupFallbackPolling(sessionId);
        }
        return; // Success, exit loop
      } catch (error) {
        this.logger.warn(`Fallback transport ${transport} failed`, error);
      }
    }
    throw new Error('All connection methods failed');
  }
 
  /**
   * Set up Socket.IO event handlers
   */
  setupSocketIOHandlers() {
    this.socket.on('progress', data => {
      this.handleProgressEvent(data);
    });
    this.socket.on('completion', data => {
      this.handleCompletionEvent(data);
    });
    this.socket.on('error', data => {
      this.handleErrorEvent(data);
    });
    this.socket.on('disconnect', reason => {
      this.handleDisconnection(reason);
    });
    this.socket.on('reconnect', () => {
      this.handleReconnection();
    });
  }
 
  /**
   * Set up SSE event handlers
   */
  setupSSEHandlers() {
    this.eventSource.addEventListener('progress', event => {
      const data = JSON.parse(event.data);
      this.handleProgressEvent(data);
    });
    this.eventSource.addEventListener('completion', event => {
      const data = JSON.parse(event.data);
      this.handleCompletionEvent(data);
    });
    this.eventSource.addEventListener('error', event => {
      const data = JSON.parse(event.data);
      this.handleErrorEvent(data);
    });
  }
 
  /**
   * Set up WebSocket event handlers
   */
  setupWebSocketHandlers() {
    this.websocket.onmessage = event => {
      try {
        const message = JSON.parse(event.data);
        switch (message.type) {
          case 'progress':
            this.handleProgressEvent(message.data);
            break;
          case 'completion':
            this.handleCompletionEvent(message.data);
            break;
          case 'error':
            this.handleErrorEvent(message.data);
            break;
        }
      } catch (error) {
        this.logger.error('Failed to parse WebSocket message', error);
      }
    };
    this.websocket.onclose = () => {
      this.handleDisconnection('WebSocket closed');
    };
  }
 
  /**
   * Set up fallback polling
   */
  async setupFallbackPolling(sessionId) {
    this.connectionType = 'polling';
    this.isConnected = true;
    this.fallbackPolling = setInterval(async () => {
      try {
        const response = await fetch(`/api/progress/poll/${sessionId}`);
        const data = await response.json();
        if (data.events && data.events.length > 0) {
          data.events.forEach(event => {
            switch (event.type) {
              case 'progress':
                this.handleProgressEvent(event.data);
                break;
              case 'completion':
                this.handleCompletionEvent(event.data);
                break;
              case 'error':
                this.handleErrorEvent(event.data);
                break;
            }
          });
        }
      } catch (error) {
        this.logger.error('Polling request failed', error);
      }
    }, 2000);
    this.logger.info('Fallback polling established');
    this.uiManager.showInfo('Using polling for updates (limited real-time capability)');
  }
 
  /**
   * Handle progress events
   */
  handleProgressEvent(data) {
    this.logger.info('Progress event received', data);
    this.triggerEvent('progress', data);
  }
 
  /**
   * Handle completion events
   */
  handleCompletionEvent(data) {
    this.logger.info('Completion event received', data);
    this.triggerEvent('completion', data);
    this.disconnect();
  }
 
  /**
   * Handle error events
   */
  handleErrorEvent(data) {
    this.logger.error('Error event received', data);
    this.triggerEvent('error', data);
  }
 
  /**
   * Handle disconnection
   */
  handleDisconnection(reason) {
    this.isConnected = false;
    this.logger.warn('Connection lost', {
      reason,
      type: this.connectionType
    });
    this.uiManager.showWarning('Real-time connection lost');
 
    // Attempt reconnection
    this.attemptReconnection();
  }
 
  /**
   * Handle reconnection
   */
  handleReconnection() {
    this.isConnected = true;
    this.reconnectAttempts = 0;
    this.logger.info('Connection restored');
    this.uiManager.showSuccess('Real-time connection restored');
  }
 
  /**
   * Attempt reconnection
   */
  async attemptReconnection() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      this.logger.error('Max reconnection attempts reached');
      this.uiManager.showError('Connection Lost', 'Unable to restore real-time connection');
      return;
    }
    this.reconnectAttempts++;
    const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
    this.logger.info('Attempting reconnection', {
      attempt: this.reconnectAttempts,
      delay
    });
    setTimeout(async () => {
      try {
        // Reconnection logic depends on connection type
        if (this.connectionType === 'socketio' && this.socket) {
          this.socket.connect();
        } else {
          // For other types, we'd need the session ID
          // This would typically be handled by the calling code
        }
      } catch (error) {
        this.logger.error('Reconnection failed', error);
        this.attemptReconnection();
      }
    }, delay);
  }
 
  /**
   * Set up connection monitoring
   */
  setupConnectionMonitoring() {
    // Monitor connection health
    setInterval(() => {
      if (this.isConnected) {
        this.checkConnectionHealth();
      }
    }, 30000); // Check every 30 seconds
  }
 
  /**
   * Check connection health
   */
  checkConnectionHealth() {
    if (this.connectionType === 'socketio' && this.socket) {
      // Socket.IO has built-in heartbeat
      if (!this.socket.connected) {
        this.handleDisconnection('Health check failed');
      }
    } else if (this.connectionType === 'sse' && this.eventSource) {
      if (this.eventSource.readyState === EventSource.CLOSED) {
        this.handleDisconnection('SSE connection closed');
      }
    } else if (this.connectionType === 'websocket' && this.websocket) {
      if (this.websocket.readyState === WebSocket.CLOSED) {
        this.handleDisconnection('WebSocket connection closed');
      }
    }
  }
 
  /**
   * Register event handler
   */
  on(event, handler) {
    if (!this.eventHandlers.has(event)) {
      this.eventHandlers.set(event, []);
    }
    this.eventHandlers.get(event).push(handler);
  }
 
  /**
   * Remove event handler
   */
  off(event, handler) {
    if (this.eventHandlers.has(event)) {
      const handlers = this.eventHandlers.get(event);
      const index = handlers.indexOf(handler);
      if (index > -1) {
        handlers.splice(index, 1);
      }
    }
  }
 
  /**
   * Trigger event
   */
  triggerEvent(event, data) {
    if (this.eventHandlers.has(event)) {
      this.eventHandlers.get(event).forEach(handler => {
        try {
          handler(data);
        } catch (error) {
          this.logger.error('Event handler error', {
            event,
            error: error.message
          });
        }
      });
    }
  }
 
  /**
   * Disconnect all connections
   */
  disconnect() {
    this.isConnected = false;
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
    if (this.eventSource) {
      this.eventSource.close();
      this.eventSource = null;
    }
    if (this.websocket) {
      this.websocket.close();
      this.websocket = null;
    }
    if (this.fallbackPolling) {
      clearInterval(this.fallbackPolling);
      this.fallbackPolling = null;
    }
    this.connectionType = null;
    this.logger.info('All real-time connections closed');
  }
 
  /**
   * Get connection status
   */
  getConnectionStatus() {
    return {
      isConnected: this.isConnected,
      connectionType: this.connectionType,
      reconnectAttempts: this.reconnectAttempts
    };
  }
}
exports.RealtimeCommunicationSubsystem = RealtimeCommunicationSubsystem;
 
},{"socket.io-client":31}],95:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.TokenNotificationSubsystem = void 0;
var _winstonLogger = require("../utils/winston-logger.js");
/**
 * Token Notification Subsystem
 * Handles user notifications for invalid/missing tokens and disabled functionality
 */
 
class TokenNotificationSubsystem {
  constructor(logger, eventBus, navigationSubsystem) {
    this.logger = logger || (0, _winstonLogger.createLogger)({
      serviceName: 'token-notification-subsystem',
      environment: 'development'
    });
    this.eventBus = eventBus;
    this.navigationSubsystem = navigationSubsystem;
    this.isInitialized = false;
    this.isDestroyed = false;
 
    // Notification state
    this.currentNotification = null;
    this.notificationElement = null;
    this.lastTokenCheck = null;
    this.checkInterval = null;
    this.logger.info('Token Notification Subsystem initialized');
  }
 
  /**
   * Initialize the subsystem
   */
  async init() {
    if (this.isInitialized || this.isDestroyed) {
      return;
    }
    try {
      this.logger.debug('Initializing Token Notification Subsystem...');
 
      // Create notification container
      this.createNotificationContainer();
 
      // Set up event listeners
      this.setupEventListeners();
 
      // Start token monitoring
      this.startTokenMonitoring();
 
      // Initial token check
      this.checkTokenStatus();
      this.isInitialized = true;
      this.eventBus.emit('tokenNotification:initialized');
      this.logger.info('Token Notification Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize Token Notification Subsystem', {
        error: error.message,
        stack: error.stack
      });
      throw error;
    }
  }
 
  /**
   * Destroy the subsystem
   */
  destroy() {
    if (this.isDestroyed) {
      return;
    }
    this.logger.debug('Destroying Token Notification Subsystem...');
 
    // Clear monitoring
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
      this.checkInterval = null;
    }
 
    // Remove notification
    this.hideNotification();
 
    // Remove notification container
    if (this.notificationElement) {
      this.notificationElement.remove();
      this.notificationElement = null;
    }
 
    // Mark as destroyed
    this.isDestroyed = true;
    this.isInitialized = false;
    this.logger.info('Token Notification Subsystem destroyed');
  }
 
  /**
   * Create notification container in DOM
   */
  createNotificationContainer() {
    // Remove existing container if it exists
    const existing = document.getElementById('token-notification-container');
    if (existing) {
      existing.remove();
    }
 
    // Create new container
    this.notificationElement = document.createElement('div');
    this.notificationElement.id = 'token-notification-container';
    this.notificationElement.className = 'token-notification-container';
    this.notificationElement.style.display = 'none';
 
    // Insert at top of main content area
    const mainContent = document.querySelector('.main-content') || document.body;
    mainContent.insertBefore(this.notificationElement, mainContent.firstChild);
    this.logger.debug('Token notification container created');
  }
 
  /**
   * Set up event listeners
   */
  setupEventListeners() {
    // Listen for token events
    this.eventBus.on('token:refreshed', () => {
      this.logger.debug('Token refreshed event received');
      this.checkTokenStatus();
    });
    this.eventBus.on('token:expired', () => {
      this.logger.debug('Token expired event received');
      this.showTokenExpiredNotification();
    });
    this.eventBus.on('token:error', () => {
      this.logger.debug('Token error event received');
      this.showTokenErrorNotification();
    });
 
    // Listen for settings changes
    this.eventBus.on('settings:updated', () => {
      this.logger.debug('Settings updated event received');
      this.checkTokenStatus();
    });
    this.logger.debug('Token notification event listeners set up');
  }
 
  /**
   * Start token monitoring
   */
  startTokenMonitoring() {
    // Check token status every 30 seconds
    this.checkInterval = setInterval(() => {
      this.checkTokenStatus();
    }, 30000);
    this.logger.debug('Token monitoring started');
  }
 
  /**
   * Check current token status and show appropriate notification
   */
  checkTokenStatus() {
    try {
      const tokenInfo = this.getTokenInfo();
      if (!tokenInfo.hasToken) {
        this.showNoTokenNotification();
      } else if (tokenInfo.timeLeft <= 0) {
        this.showTokenExpiredNotification();
      } else if (tokenInfo.timeLeft <= 300) {
        // 5 minutes
        this.showTokenExpiringNotification(tokenInfo.timeLeft);
      } else {
        this.hideNotification();
      }
      this.lastTokenCheck = Date.now();
    } catch (error) {
      this.logger.error('Error checking token status', {
        error: error.message
      });
      this.showTokenErrorNotification();
    }
  }
 
  /**
   * Get token information from localStorage
   */
  getTokenInfo() {
    try {
      const token = localStorage.getItem('pingone_worker_token');
      const expiry = localStorage.getItem('pingone_token_expiry');
      if (!token || !expiry) {
        return {
          hasToken: false,
          timeLeft: 0
        };
      }
      const expiryTime = parseInt(expiry, 10);
      const currentTime = Math.floor(Date.now() / 1000);
      const timeLeft = expiryTime - currentTime;
      return {
        hasToken: true,
        timeLeft: Math.max(0, timeLeft),
        token: token.substring(0, 20) + '...' // Truncated for logging
      };
    } catch (error) {
      this.logger.error('Error getting token info', {
        error: error.message
      });
      return {
        hasToken: false,
        timeLeft: 0
      };
    }
  }
 
  /**
   * Show notification for missing token
   */
  showNoTokenNotification() {
    const message = `
            <div class="token-notification-content">
                <div class="token-notification-icon">🔒</div>
                <div class="token-notification-text">
                    <h4>Authentication Required</h4>
                    <p>No valid PingOne token found. Most functionality is disabled until you authenticate.</p>
                    <p><strong>What you can do:</strong></p>
                    <ul>
                        <li>Go to <strong>Settings</strong> to configure your PingOne credentials</li>
                        <li>Use the <strong>Get Token</strong> button to authenticate</li>
                        <li>Check the token status widget in the sidebar</li>
                    </ul>
                </div>
                <div class="token-notification-actions">
                    <button id="go-to-settings-btn" class="btn btn-primary btn-sm">Go to Settings</button>
                    <button onclick="this.parentElement.parentElement.parentElement.style.display='none'" class="btn btn-secondary btn-sm">Dismiss</button>
                </div>
            </div>
        `;
    this.showNotification(message, 'no-token');
  }
 
  /**
   * Show notification for expired token
   */
  showTokenExpiredNotification() {
    const message = `
            <div class="token-notification-content">
                <div class="token-notification-icon">⏰</div>
                <div class="token-notification-text">
                    <h4>Token Expired</h4>
                    <p>Your PingOne authentication token has expired. Please get a new token to continue using the application.</p>
                </div>
                <div class="token-notification-actions">
                    <button onclick="window.app?.subsystems?.globalTokenManager?.refreshToken?.()" class="btn btn-warning btn-sm">Refresh Token</button>
                    <button onclick="this.parentElement.parentElement.parentElement.style.display='none'" class="btn btn-secondary btn-sm">Dismiss</button>
                </div>
            </div>
        `;
    this.showNotification(message, 'expired-token');
  }
 
  /**
   * Show notification for expiring token
   */
  showTokenExpiringNotification(timeLeft) {
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    const timeString = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
    const message = `
            <div class="token-notification-content">
                <div class="token-notification-icon">⚠️</div>
                <div class="token-notification-text">
                    <h4>Token Expiring Soon</h4>
                    <p>Your PingOne token will expire in <strong>${timeString}</strong>. Consider refreshing it to avoid interruption.</p>
                </div>
                <div class="token-notification-actions">
                    <button onclick="window.app?.subsystems?.globalTokenManager?.refreshToken?.()" class="btn btn-warning btn-sm">Refresh Now</button>
                    <button onclick="this.parentElement.parentElement.parentElement.style.display='none'" class="btn btn-secondary btn-sm">Dismiss</button>
                </div>
            </div>
        `;
    this.showNotification(message, 'expiring-token');
  }
 
  /**
   * Show notification for token error
   */
  showTokenErrorNotification() {
    const message = `
            <div class="token-notification-content">
                <div class="token-notification-icon">❌</div>
                <div class="token-notification-text">
                    <h4>Token Error</h4>
                    <p>There was an error with your authentication token. Please check your settings and try again.</p>
                </div>
                <div class="token-notification-actions">
                    <button onclick="window.location.hash='settings'" class="btn btn-primary btn-sm">Check Settings</button>
                    <button onclick="this.parentElement.parentElement.parentElement.style.display='none'" class="btn btn-secondary btn-sm">Dismiss</button>
                </div>
            </div>
        `;
    this.showNotification(message, 'error-token');
  }
 
  /**
   * Show notification with given content and type
   */
  showNotification(content, type) {
    if (!this.notificationElement) {
      this.logger.warn('Notification element not available');
      return;
    }
 
    // Don't show the same notification repeatedly
    if (this.currentNotification === type) {
      return;
    }
    this.notificationElement.innerHTML = content;
    this.notificationElement.className = `token-notification-container ${type}`;
    this.notificationElement.style.display = 'block';
    this.currentNotification = type;
    this.logger.debug('Token notification shown', {
      type
    });
 
    // Add event listener for the 'Go to Settings' button if it exists
    const goToSettingsBtn = this.notificationElement.querySelector('#go-to-settings-btn');
    if (goToSettingsBtn) {
      goToSettingsBtn.addEventListener('click', e => {
        e.preventDefault();
        if (this.navigationSubsystem) {
          this.navigationSubsystem.navigateToView('settings');
        } else {
          this.logger.error('NavigationSubsystem not available.');
          // Fallback for safety
          window.location.hash = 'settings';
        }
      });
    }
  }
 
  /**
   * Hide current notification
   */
  hideNotification() {
    if (this.notificationElement) {
      this.notificationElement.style.display = 'none';
      this.notificationElement.innerHTML = '';
    }
    this.currentNotification = null;
    this.logger.debug('Token notification hidden');
  }
}
exports.TokenNotificationSubsystem = TokenNotificationSubsystem;
var _default = exports.default = TokenNotificationSubsystem;
 
},{"../utils/winston-logger.js":99}],96:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ViewManagementSubsystem = void 0;
/**
 * View Management Subsystem
 * 
 * Handles all view transitions, navigation, and view-specific initialization.
 * Manages the single-page application navigation and view state.
 */
 
class ViewManagementSubsystem {
  constructor(logger, uiManager) {
    this.logger = logger;
    this.uiManager = uiManager;
 
    // View state management
    this.currentView = 'home';
    this.previousView = null;
    this.viewHistory = [];
    this.viewInitializers = new Map();
    this.logger.info('View Management Subsystem initialized with default home view');
  }
 
  /**
   * Initialize the view management subsystem
   */
  async init() {
    try {
      this.setupNavigationListeners();
      this.registerViewInitializers();
      await this.showInitialView();
      this.logger.info('View Management Subsystem initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize View Management Subsystem', error);
      throw error;
    }
  }
 
  /**
   * Set up navigation event listeners
   */
  setupNavigationListeners() {
    // Navigation items
    const navItems = document.querySelectorAll('[data-view]');
    navItems.forEach(item => {
      item.addEventListener('click', async e => {
        e.preventDefault();
        const view = item.getAttribute('data-view');
        await this.showView(view);
      });
    });
 
    // Browser back/forward buttons
    window.addEventListener('popstate', e => {
      if (e.state && e.state.view) {
        this.showView(e.state.view, false);
      }
    });
 
    // Keyboard navigation
    document.addEventListener('keydown', e => {
      if (e.ctrlKey || e.metaKey) {
        this.handleKeyboardNavigation(e);
      }
    });
  }
 
  /**
   * Register view initializers
   */
  registerViewInitializers() {
    // Import view initializer
    this.viewInitializers.set('import', async () => {
      await this.initializeImportView();
    });
 
    // Export view initializer
    this.viewInitializers.set('export', async () => {
      await this.initializeExportView();
    });
 
    // Modify view initializer
    this.viewInitializers.set('modify', async () => {
      await this.initializeModifyView();
    });
 
    // Delete view initializer
    this.viewInitializers.set('delete-csv', async () => {
      await this.initializeDeleteView();
    });
 
    // Settings view initializer
    this.viewInitializers.set('settings', async () => {
      await this.initializeSettingsView();
    });
 
    // Logs view initializer
    this.viewInitializers.set('logs', async () => {
      await this.initializeLogsView();
    });
 
    // History view initializer
    this.viewInitializers.set('history', async () => {
      await this.initializeHistoryView();
    });
 
    // Analytics view initializer
    this.viewInitializers.set('analytics', async () => {
      await this.initializeAnalyticsView();
    });
  }
 
  /**
   * Show a specific view
   */
  async showView(view) {
    let updateHistory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    if (!view || view === this.currentView) {
      return;
    }
    try {
      this.logger.info('Switching to view', {
        from: this.currentView,
        to: view
      });
 
      // Validate view exists
      if (!this.isValidView(view)) {
        if (this.uiManager && typeof this.uiManager.showError === 'function') {
          this.uiManager.showError('Navigation Error', `Invalid view: ${view}`);
        }
        return;
      }
 
      // Store previous view
      this.previousView = this.currentView;
 
      // Hide current view
      this.hideCurrentView();
 
      // Show new view
      await this.displayView(view);
 
      // Update navigation state
      this.updateNavigationState(view);
 
      // Update browser history
      if (updateHistory) {
        this.updateBrowserHistory(view);
      }
 
      // Initialize view-specific logic
      await this.initializeView(view);
 
      // Update view state
      this.currentView = view;
      this.viewHistory.push(view);
 
      // Update page title
      this.updatePageTitle(view);
 
      // Trigger view change event
      this.triggerViewChangeEvent(view, this.previousView);
    } catch (error) {
      this.logger.error('Failed to switch view', {
        view,
        error: error.message
      });
      if (this.uiManager && typeof this.uiManager.showError === 'function') {
        this.uiManager.showError('Navigation Error', `Failed to switch to ${view} view: ${error.message}`);
      }
    }
  }
 
  /**
   * Hide the current view
   */
  hideCurrentView() {
    const currentViewElement = document.getElementById(`${this.currentView}-view`);
    if (currentViewElement) {
      currentViewElement.style.display = 'none';
      currentViewElement.classList.remove('active');
    }
  }
 
  /**
   * Display the specified view
   */
  async displayView(view) {
    const viewElement = document.getElementById(`${view}-view`);
    if (!viewElement) {
      throw new Error(`View element not found: ${view}-view`);
    }
 
    // Show view with animation
    viewElement.style.display = 'block';
    viewElement.classList.add('active');
 
    // Add fade-in animation
    viewElement.style.opacity = '0';
    viewElement.style.transition = 'opacity 0.3s ease-in-out';
 
    // Trigger reflow and fade in
    requestAnimationFrame(() => {
      viewElement.style.opacity = '1';
    });
  }
 
  /**
   * Update navigation state
   */
  updateNavigationState(view) {
    // Update navigation items
    const navItems = document.querySelectorAll('[data-view]');
    navItems.forEach(item => {
      const itemView = item.getAttribute('data-view');
      if (itemView === view) {
        item.classList.add('active');
      } else {
        item.classList.remove('active');
      }
    });
 
    // Update page title
    this.updatePageTitle(view);
  }
 
  /**
   * Update browser history
   */
  updateBrowserHistory(view) {
    const state = {
      view,
      timestamp: Date.now()
    };
    const title = this.getViewTitle(view);
    const url = `#${view}`;
    history.pushState(state, title, url);
  }
 
  /**
   * Initialize view-specific functionality
   */
  async initializeView(view) {
    const initializer = this.viewInitializers.get(view);
    if (initializer) {
      try {
        await initializer();
      } catch (error) {
        this.logger.error('View initialization failed', {
          view,
          error: error.message
        });
      }
    }
  }
 
  /**
   * Initialize import view
   */
  async initializeImportView() {
    // Load populations for import dropdown
    if (window.app && typeof window.app.loadPopulations === 'function') {
      await window.app.loadPopulations('import-population-select');
    }
 
    // Reset file input
    const fileInput = document.getElementById('csv-file');
    if (fileInput) {
      fileInput.value = '';
    }
 
    // Reset progress display
    this.resetProgressDisplay();
  }
 
  /**
   * Initialize export view
   * CRITICAL: This method initializes the export view and loads populations
   * DO NOT change the subsystem reference path without verifying App class structure
   * Last fixed: 2025-07-21 - Fixed incorrect reference to export manager
   */
  async initializeExportView() {
    this.logger.debug('🔄 VIEW: Initializing export view...');
 
    // Load populations for export dropdown using correct subsystem reference
    if (window.app && window.app.subsystems && window.app.subsystems.exportManager) {
      this.logger.debug('🔄 VIEW: Found export manager, loading populations...');
      if (typeof window.app.subsystems.exportManager.loadPopulations === 'function') {
        await window.app.subsystems.exportManager.loadPopulations();
        this.logger.info('🔄 VIEW: Export populations loaded successfully');
      } else {
        this.logger.error('🔄 VIEW: Export manager loadPopulations method not found');
      }
    } else {
      this.logger.error('🔄 VIEW: Export manager not found in app subsystems', {
        hasApp: !!window.app,
        hasSubsystems: !!(window.app && window.app.subsystems),
        availableSubsystems: window.app && window.app.subsystems ? Object.keys(window.app.subsystems) : []
      });
    }
  }
 
  /**
   * Initialize modify view
   */
  async initializeModifyView() {
    // Load populations for modify dropdown
    if (window.app && typeof window.app.loadPopulations === 'function') {
      await window.app.loadPopulations('modify-population-select');
    }
 
    // Reset file input
    const fileInput = document.getElementById('modify-csv-file');
    if (fileInput) {
      fileInput.value = '';
    }
  }
 
  /**
   * Initialize delete view
   */
  async initializeDeleteView() {
    // Load populations for delete dropdown
    if (window.deleteManager && typeof window.deleteManager.loadPopulations === 'function') {
      await window.deleteManager.loadPopulations();
    }
  }
 
  /**
   * Initialize settings view
   */
  async initializeSettingsView() {
    // Load current settings
    if (window.app && typeof window.app.loadSettings === 'function') {
      await window.app.loadSettings();
    }
  }
 
  /**
   * Initialize logs view
   */
  async initializeLogsView() {
    // Load logs
    if (window.logManager && typeof window.logManager.loadLogs === 'function') {
      await window.logManager.loadLogs();
    }
  }
 
  /**
   * Initialize history view
   */
  async initializeHistoryView() {
    try {
      // Initialize history UI component if available
      if (this.app && this.app.subsystems && this.app.subsystems.history) {
        this.logger.debug('Initializing history view with HistorySubsystem');
 
        // The history UI component will be initialized by the main app
        // Just ensure the view container exists
        const historyView = document.getElementById('history-view');
        if (!historyView) {
          this.logger.warn('History view container not found');
        }
      } else {
        this.logger.warn('HistorySubsystem not available for history view initialization');
      }
    } catch (error) {
      this.logger.error('Failed to initialize history view:', error);
    }
  }
 
  /**
   * Initialize analytics view
   */
  async initializeAnalyticsView() {
    try {
      this.logger.debug('Initializing analytics view');
 
      // Check if analytics dashboard is available
      if (window.app && window.app.analyticsDashboardUI) {
        this.logger.debug('Analytics dashboard UI available, ensuring visibility');
 
        // Make sure analytics dashboard is visible when analytics view is shown
        const analyticsContainer = document.getElementById('analytics-dashboard');
        if (analyticsContainer) {
          analyticsContainer.style.display = 'block';
          this.logger.debug('Analytics dashboard container made visible');
        } else {
          this.logger.warn('Analytics dashboard container not found');
        }
      } else {
        this.logger.warn('Analytics dashboard UI not available for analytics view initialization');
      }
    } catch (error) {
      this.logger.error('Failed to initialize analytics view:', error);
    }
  }
 
  /**
   * Show initial view based on URL hash or default
   */
  async showInitialView() {
    let initialView = 'home';
 
    // Check URL hash for the initial view
    const hash = window.location.hash.substring(1);
    if (hash && this.isValidView(hash)) {
      initialView = hash;
    }
    await this.showView(initialView, false);
  }
 
  /**
   * Check if view is valid
   */
  isValidView(view) {
    const validViews = ['home', 'import', 'export', 'modify', 'delete-csv', 'settings', 'logs', 'history', 'analytics'];
    return validViews.includes(view);
  }
 
  /**
   * Get view title
   */
  getViewTitle(view) {
    const titles = {
      'import': 'Import Users',
      'export': 'Export Users',
      'modify': 'Modify Users',
      'delete-csv': 'Delete Users',
      'settings': 'Settings',
      'logs': 'Logs',
      'history': 'History',
      'analytics': 'Analytics Dashboard'
    };
    return titles[view] || 'PingOne Import Tool';
  }
 
  /**
   * Update page title
   */
  updatePageTitle(view) {
    const title = this.getViewTitle(view);
    document.title = `${title} - PingOne Import Tool`;
  }
 
  /**
   * Handle keyboard navigation
   */
  handleKeyboardNavigation(e) {
    const keyMap = {
      '1': 'import',
      '2': 'export',
      '3': 'modify',
      '4': 'delete-csv',
      '5': 'settings',
      '6': 'logs',
      '7': 'history'
    };
    const view = keyMap[e.key];
    if (view) {
      e.preventDefault();
      this.showView(view);
    }
  }
 
  /**
   * Reset progress display
   */
  resetProgressDisplay() {
    // Use uiManager to hide progress and reset bar
    if (this.uiManager && typeof this.uiManager.hideProgress === 'function') {
      this.uiManager.hideProgress();
    }
    if (this.uiManager && typeof this.uiManager.updateProgress === 'function') {
      this.uiManager.updateProgress(0, 1, ''); // Reset bar
    }
  }
 
  /**
   * Trigger view change event
   */
  triggerViewChangeEvent(newView, oldView) {
    const event = new CustomEvent('viewChanged', {
      detail: {
        newView,
        oldView,
        timestamp: Date.now()
      }
    });
    document.dispatchEvent(event);
  }
 
  /**
   * Go back to previous view
   */
  async goBack() {
    if (this.previousView) {
      await this.showView(this.previousView);
    }
  }
 
  /**
   * Get current view
   */
  getCurrentView() {
    return this.currentView;
  }
 
  /**
   * Get view history
   */
  getViewHistory() {
    return [...this.viewHistory];
  }
 
  /**
   * Clear view history
   */
  clearViewHistory() {
    this.viewHistory = [];
  }
}
exports.ViewManagementSubsystem = ViewManagementSubsystem;
 
},{}],97:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.BrowserLoggingService = void 0;
exports.createLogger = createLogger;
exports.logger = exports.default = void 0;
/**
 * Browser-Compatible Logging Service
 * 
 * Provides unified logging for browser environment with:
 * - Correlation IDs for request tracking
 * - Structured logging with metadata
 * - Console and server transports
 * - Log level filtering
 * - Performance monitoring
 */
 
class BrowserLoggingService {
  constructor() {
    let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    this.serviceName = options.serviceName || 'pingone-import-client';
    this.environment = options.environment || 'development';
    this.logLevel = options.logLevel || this.getDefaultLogLevel();
    this.enableConsole = options.enableConsole !== false;
    this.enableServer = options.enableServer !== false;
 
    // Log levels hierarchy
    this.levels = {
      error: 0,
      warn: 1,
      info: 2,
      debug: 3
    };
 
    // Correlation ID for request tracking
    this.correlationId = this.generateCorrelationId();
 
    // Performance tracking
    this.performanceMarks = new Map();
    this.initializeTransports();
  }
 
  /**
   * Get default log level based on environment
   */
  getDefaultLogLevel() {
    switch (this.environment) {
      case 'production':
        return 'info';
      case 'test':
        return 'warn';
      default:
        return 'debug';
    }
  }
 
  /**
   * Generate correlation ID for request tracking
   */
  generateCorrelationId() {
    return `${this.serviceName}-${Date.now()}-${Math.random().toString(36).substr(2, 8)}`;
  }
 
  /**
   * Initialize logging transports
   */
  initializeTransports() {
    this.transports = [];
    if (this.enableConsole) {
      this.transports.push({
        name: 'console',
        log: this.logToConsole.bind(this)
      });
    }
    if (this.enableServer) {
      this.transports.push({
        name: 'server',
        log: this.logToServer.bind(this)
      });
    }
  }
 
  /**
   * Check if log level should be processed
   */
  shouldLog(level) {
    return this.levels[level] <= this.levels[this.logLevel];
  }
 
  /**
   * Format log entry with metadata
   */
  formatLogEntry(level, message) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    return {
      timestamp: new Date().toISOString(),
      level: level.toUpperCase(),
      message,
      service: this.serviceName,
      environment: this.environment,
      correlationId: this.correlationId,
      source: 'client',
      url: window.location.href,
      userAgent: navigator.userAgent,
      ...meta
    };
  }
 
  /**
   * Log to console with formatting
   */
  logToConsole(level, message) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    if (!this.shouldLog(level)) return;
    const entry = this.formatLogEntry(level, message, meta);
    const timestamp = entry.timestamp;
    const correlationId = entry.correlationId.slice(-8);
    let consoleMessage = `[${timestamp}] [${correlationId}] [${entry.service}] ${level.toUpperCase()}: ${message}`;
    if (Object.keys(meta).length > 0) {
      consoleMessage += `\n${JSON.stringify(meta, null, 2)}`;
    }
    switch (level) {
      case 'error':
        console.error(consoleMessage);
        break;
      case 'warn':
        console.warn(consoleMessage);
        break;
      case 'info':
        console.info(consoleMessage);
        break;
      case 'debug':
        console.debug(consoleMessage);
        break;
      default:
        console.log(consoleMessage);
    }
  }
 
  /**
   * Log to server via API endpoint
   */
  async logToServer(level, message) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    try {
      const entry = this.formatLogEntry(level, message, meta);
      await fetch('/api/logs/client', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(entry)
      });
    } catch (error) {
      // Silently fail to avoid infinite loops
      if (this.enableConsole) {
        console.warn('Failed to send log to server:', error.message);
      }
    }
  }
 
  /**
   * Main logging method
   */
  log(level, message) {
    let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    if (!this.shouldLog(level)) return;
    this.transports.forEach(transport => {
      try {
        transport.log(level, message, meta);
      } catch (error) {
        console.error(`Error in ${transport.name} transport:`, error);
      }
    });
  }
 
  /**
   * Convenience methods
   */
  error(message) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('error', message, meta);
  }
  warn(message) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('warn', message, meta);
  }
  info(message) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('info', message, meta);
  }
  debug(message) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    this.log('debug', message, meta);
  }
 
  /**
   * Performance monitoring
   */
  startTimer(label) {
    this.performanceMarks.set(label, performance.now());
    this.debug(`Timer started: ${label}`);
  }
  endTimer(label) {
    let meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    const startTime = this.performanceMarks.get(label);
    if (!startTime) {
      this.warn(`Timer not found: ${label}`);
      return 0;
    }
    const duration = performance.now() - startTime;
    this.performanceMarks.delete(label);
    this.info(`Timer completed: ${label}`, {
      duration: `${duration.toFixed(2)}ms`,
      ...meta
    });
    return duration;
  }
 
  /**
   * Create child logger with additional context
   */
  child() {
    let additionalMeta = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const childLogger = new BrowserLoggingService({
      serviceName: this.serviceName,
      environment: this.environment,
      logLevel: this.logLevel,
      enableConsole: this.enableConsole,
      enableServer: this.enableServer
    });
 
    // Override formatLogEntry to include additional metadata
    const originalFormatLogEntry = childLogger.formatLogEntry.bind(childLogger);
    childLogger.formatLogEntry = function (level, message) {
      let meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      return originalFormatLogEntry(level, message, {
        ...additionalMeta,
        ...meta
      });
    };
    return childLogger;
  }
 
  /**
   * Set correlation ID (useful for request tracking)
   */
  setCorrelationId(correlationId) {
    this.correlationId = correlationId;
  }
 
  /**
   * Get current correlation ID
   */
  getCorrelationId() {
    return this.correlationId;
  }
}
 
/**
 * Create logger instance
 */
exports.BrowserLoggingService = BrowserLoggingService;
function createLogger() {
  let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return new BrowserLoggingService(options);
}
 
/**
 * Default logger instance
 */
const logger = exports.logger = createLogger({
  serviceName: 'pingone-import-client'
});
var _default = exports.default = BrowserLoggingService;
 
},{}],98:[function(require,module,exports){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.debugLog = void 0;
exports.getClientDebugLogger = getClientDebugLogger;
/**
 * Client-Side Debug Logger
 * 
 * Browser-compatible version of the debug logger that sends logs to the server.
 */
 
class ClientDebugLogger {
  constructor() {
    this.sessionId = this.generateSessionId();
    this.isClient = true;
 
    // Initialize with session start
    this.log('SESSION_START', 'Client debug logging session started', {
      timestamp: new Date().toISOString(),
      sessionId: this.sessionId,
      userAgent: navigator.userAgent,
      url: window.location.href
    });
  }
  generateSessionId() {
    return 'client_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }
  formatLogEntry(level, category, message) {
    let data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    const timestamp = new Date().toISOString();
    const entry = {
      timestamp,
      sessionId: this.sessionId,
      level: level.toUpperCase(),
      category: category.toUpperCase(),
      message,
      environment: 'client',
      url: window.location.href,
      data: data || {}
    };
 
    // Format as readable string
    const formattedEntry = `[${timestamp}] [${this.sessionId}] [CLIENT] [${level.toUpperCase()}] [${category.toUpperCase()}] ${message}`;
    const dataString = Object.keys(data).length > 0 ? `\n  Data: ${JSON.stringify(data, null, 2)}` : '';
    return formattedEntry + dataString + '\n' + '-'.repeat(80) + '\n';
  }
  async sendToServer(entry) {
    try {
      await fetch('/api/debug-log', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          entry
        })
      });
    } catch (error) {
      console.error('Failed to send debug log to server:', error);
    }
  }
 
  // Main logging method
  log(category, message) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const entry = this.formatLogEntry('info', category, message, data);
    this.sendToServer(entry);
 
    // Also log to console in development
    console.log(`🐛 [${category.toUpperCase()}] ${message}`, data);
  }
 
  // Error logging
  error(category, message) {
    let error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    let data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    const errorData = {
      ...data,
      error: error ? {
        message: error.message,
        stack: error.stack,
        name: error.name
      } : null
    };
    const entry = this.formatLogEntry('error', category, message, errorData);
    this.sendToServer(entry);
 
    // Always log errors to console
    console.error(`🚨 [${category.toUpperCase()}] ${message}`, errorData);
  }
 
  // Warning logging
  warn(category, message) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const entry = this.formatLogEntry('warn', category, message, data);
    this.sendToServer(entry);
    console.warn(`⚠️ [${category.toUpperCase()}] ${message}`, data);
  }
 
  // Debug logging
  debug(category, message) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const entry = this.formatLogEntry('debug', category, message, data);
    this.sendToServer(entry);
    console.debug(`🔍 [${category.toUpperCase()}] ${message}`, data);
  }
 
  // Event logging
  event(category, eventName) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    const eventData = {
      eventName,
      ...data
    };
    const entry = this.formatLogEntry('event', category, `Event: ${eventName}`, eventData);
    this.sendToServer(entry);
    console.log(`📊 [${category.toUpperCase()}] Event: ${eventName}`, eventData);
  }
 
  // Performance logging
  performance(category, operation, duration) {
    let data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    const perfData = {
      operation,
      duration: `${duration}ms`,
      ...data
    };
    const entry = this.formatLogEntry('perf', category, `Performance: ${operation}`, perfData);
    this.sendToServer(entry);
    console.log(`⚡ [${category.toUpperCase()}] Performance: ${operation} (${duration}ms)`, perfData);
  }
 
  // Navigation logging
  navigation(from, to) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    this.event('navigation', 'view_change', {
      from,
      to,
      ...data
    });
  }
 
  // API logging
  api(method, url, status, duration) {
    let data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
    this.event('api', 'request', {
      method,
      url,
      status,
      duration: `${duration}ms`,
      ...data
    });
  }
 
  // User action logging
  userAction(action, element) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    this.event('user', action, {
      element,
      ...data
    });
  }
 
  // System state logging
  systemState(component, state) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    this.log('system', `${component} state: ${state}`, data);
  }
 
  // Feature flag logging
  featureFlag(flag, enabled) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    this.log('feature', `Feature flag ${flag}: ${enabled ? 'enabled' : 'disabled'}`, data);
  }
 
  // Subsystem logging
  subsystem(name, action) {
    let data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    this.log('subsystem', `${name}: ${action}`, data);
  }
}
 
// Create singleton instance
let clientDebugLogger = null;
function getClientDebugLogger() {
  if (!clientDebugLogger) {
    clientDebugLogger = new ClientDebugLogger();
  }
  return clientDebugLogger;
}
 
// Convenience exports
const debugLog = exports.debugLog = {
  log: (category, message, data) => getClientDebugLogger().log(category, message, data),
  error: (category, message, error, data) => getClientDebugLogger().error(category, message, error, data),
  warn: (category, message, data) => getClientDebugLogger().warn(category, message, data),
  debug: (category, message, data) => getClientDebugLogger().debug(category, message, data),
  event: (category, eventName, data) => getClientDebugLogger().event(category, eventName, data),
  performance: (category, operation, duration, data) => getClientDebugLogger().performance(category, operation, duration, data),
  navigation: (from, to, data) => getClientDebugLogger().navigation(from, to, data),
  api: (method, url, status, duration, data) => getClientDebugLogger().api(method, url, status, duration, data),
  userAction: (action, element, data) => getClientDebugLogger().userAction(action, element, data),
  systemState: (component, state, data) => getClientDebugLogger().systemState(component, state, data),
  featureFlag: (flag, enabled, data) => getClientDebugLogger().featureFlag(flag, enabled, data),
  subsystem: (name, action, data) => getClientDebugLogger().subsystem(name, action, data)
};
var _default = exports.default = debugLog;
 
},{}],99:[function(require,module,exports){
arguments[4][70][0].apply(exports,arguments)
},{"_process":29,"dup":70}],100:[function(require,module,exports){
(function (process){(function (){
"use strict";
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.FEATURE_FLAGS = void 0;
exports.getEnabledFeatures = getEnabledFeatures;
exports.getFeatureFlagStatus = getFeatureFlagStatus;
exports.isFeatureEnabled = isFeatureEnabled;
exports.setFeatureFlag = setFeatureFlag;
/**
 * Feature Flags Configuration
 * 
 * Centralized feature flag management for gradual subsystem rollout
 * and A/B testing capabilities.
 */
 
const FEATURE_FLAGS = exports.FEATURE_FLAGS = {
  // Logging and monitoring
  USE_CENTRALIZED_LOGGING: true,
  ENABLE_PERFORMANCE_MONITORING: true,
  ENABLE_ERROR_TRACKING: true,
  // Subsystem rollout flags
  USE_NAVIGATION_SUBSYSTEM: false,
  // Disabled to avoid conflict with ViewManagementSubsystem
  USE_CONNECTION_MANAGER: true,
  USE_AUTH_MANAGEMENT: true,
  USE_VIEW_MANAGEMENT: true,
  USE_OPERATION_MANAGER: true,
  USE_IMPORT_SUBSYSTEM: true,
  USE_EXPORT_SUBSYSTEM: true,
  USE_REALTIME_SUBSYSTEM: true,
  USE_ADVANCED_REALTIME: true,
  USE_ANALYTICS_DASHBOARD: true,
  // CRITICAL: Enable analytics dashboard functionality
 
  // UI enhancements
  ENABLE_ADVANCED_PROGRESS_UI: true,
  ENABLE_DRAG_DROP_IMPROVEMENTS: true,
  ENABLE_KEYBOARD_SHORTCUTS: false,
  // API optimizations
  ENABLE_REQUEST_BATCHING: false,
  ENABLE_RESPONSE_CACHING: false,
  ENABLE_RETRY_LOGIC: true,
  // Development and debugging
  ENABLE_DEBUG_MODE: process.env.NODE_ENV === 'development',
  ENABLE_VERBOSE_LOGGING: process.env.NODE_ENV === 'development',
  SHOW_PERFORMANCE_METRICS: process.env.NODE_ENV === 'development'
};
 
/**
 * Check if a feature is enabled
 */
function isFeatureEnabled(featureName) {
  return FEATURE_FLAGS[featureName] === true;
}
 
/**
 * Get all enabled features
 */
function getEnabledFeatures() {
  return Object.entries(FEATURE_FLAGS).filter(_ref => {
    let [_, enabled] = _ref;
    return enabled;
  }).map(_ref2 => {
    let [feature, _] = _ref2;
    return feature;
  });
}
 
/**
 * Get feature flag status for debugging
 */
function getFeatureFlagStatus() {
  return {
    total: Object.keys(FEATURE_FLAGS).length,
    enabled: getEnabledFeatures().length,
    flags: FEATURE_FLAGS,
    environment: process.env.NODE_ENV || 'development'
  };
}
 
/**
 * Runtime feature flag override (for testing)
 */
function setFeatureFlag(featureName, enabled) {
  if (process.env.NODE_ENV === 'development') {
    FEATURE_FLAGS[featureName] = enabled;
    console.log(`Feature flag ${featureName} set to ${enabled}`);
  } else {
    console.warn('Feature flags can only be modified in development mode');
  }
}
var _default = exports.default = FEATURE_FLAGS;
 
}).call(this)}).call(this,require('_process'))
},{"_process":29}]},{},[76]);